ArrayList replaceAll() retains only the elements in this list that are contained in the specified method argument collection. Rest all elements are removed from the list. This method is exact opposite to removeAll() method.
1. ArrayList replaceAll() method
The replaceAll() method takes single argument of type UnaryOperator. The UnaryOperator interface is a functional interface that has a single abstract method named apply that returns a result of the same object type as the operand.
We have seen UnaryOperator
in action in usually lambda expressions taking a single argument in form of 'x-> do something with x'
.
public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { elementData[i] = operator.apply((E) elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
Method parameter – UnaryOperator expression.
Method returns – void
.
Method throws – ConcurrentModificationException
if list is modified while replaceAll()
method is not finished.
2. ArrayList replaceAll() example
Java program to use replaceAll()
method to transform all the elements of an arraylist using a lambda expression.
2.1. Inline lambda expression
We can use the inline lambda expressions in case the we have to execute only single statement.
import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E")); System.out.println(alphabets); alphabets.replaceAll( e -> e.toLowerCase() ); System.out.println(alphabets); } }
Program output.
[A, B, C, D, E] [a, b, c, d, e]
2.2. Custom UnaryOperator implemetation
Create a new class which implements UnaryOperator
to executed a more complex logic on each element of arraylist.
import java.util.ArrayList; import java.util.Arrays; import java.util.function.UnaryOperator; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E")); System.out.println(alphabets); alphabets.replaceAll( new MyOperator() ); System.out.println(alphabets); } } class MyOperator implements UnaryOperator<String> { @Override public String apply(String t) { return t.toLowerCase(); } }
Program output.
[A, B, C, D, E] [a, b, c, d, e]
That’s all for the ArrayList replaceAll() method in Java.
Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs