Java ArrayList replaceAll()

The syntax of the replaceAll() method is:

arraylist.replaceAll(UnaryOperator<E> operator)

Here, arraylist is an object of the ArrayList class.


replaceAll() Parameters

The replaceAll() method takes a single parameter.

  • operator - operation to be applied to each element

replaceAll() Return Value

The replaceAll() method does not return any values. Rather, it replaces all value of the arraylist with new values from operator.


Example 1: Change All Elements to Uppercase

Output

ArrayList: [java, javascript, swift, python]
Updated ArrayList: [JAVA, JAVASCRIPT, SWIFT, PYTHON]

In the above example, we have created an arraylist named languages. Notice the line,

languages.replaceAll(e -> e.toUpperCase());

Here,

  • e -> e.toUpperCase() is a lambda expression. It converts all elements of the arraylist into uppercase. To learn more, visit Java Lambda Expression.
  • replaceAll() - Replaces all elements of the arraylist into uppercase.

Example 2: Multiply All Elements of ArrayList by 2

Output

ArrayList: [1, 2, 3]
Updated ArrayList: [2, 4, 6]

In the above example, we have created an arraylist named numbers. Notice the line,

numbers.replaceAll(e -> e * 2);

Here,

  • e -> e * 2 - multiply each element of the arraylist by 2
  • replaceAll() - replaces all elements of the arraylist with results of e -> e * 2

Note: We can also use the Collections.replace() method to perform the exact operation in Java.