In Java 8 and later, replaceAll(operator) replaces every element of an ArrayList with the result of applying a function to it. The function is a UnaryOperator<E>: it takes one element and returns a value of the same type.
The list is changed in place: the size and the positions stay the same, only the values change. It is a shorter form of a loop that calls set(i, f(get(i))). Do not confuse it with String.replaceAll, which replaces text using a regular expression.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe. replaceAll was added in Java 8 as a default method of List; ArrayList overrides it with the same behavior.
Syntax
Pass a lambda or method reference that maps an element to its new value.
Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b"));
list.replaceAll(s -> s.toUpperCase()); // [A, B]
list.replaceAll(String::toLowerCase); // [a, b]
Call
What it does
list.replaceAll(x -> ...)
A lambda computes each new value.
list.replaceAll(String::trim)
A method reference for String lists.
list.replaceAll(n -> n * 2)
Doubles every number in a List<Integer>.
Collections.replaceAll(list, oldVal, newVal)
A different method: swaps one value for another everywhere.
The operator runs once per element, from index 0 to the end. Its result must have the list's element type: for a List<String>, the operator must return a String.
Library declarations
Java
// java.util.ArrayList<E>
public void replaceAll(UnaryOperator<E> operator)
// Declared in List<E> (default method since Java 8)
// java.util.function.UnaryOperator<T> extends Function<T, T>
T apply(T t)
Parameters
Parameter
Description
operator (UnaryOperator<E>)
The function applied to each element. Must not be null.