Java ArrayList replaceAll()

In Java, ArrayList.replaceAll() retains only the elements in this list that are present in the specified method argument collection. Rest all elements are removed from the list. This method is exactly the opposite of removeAll() method.

1. ArrayList.replaceAll() API

The replaceAll() method takes a single argument of type UnaryOperator. The UnaryOperator interface is a functional interface with 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);

Method parameterUnaryOperator expression.
Method returnsvoid.
Method throwsConcurrentModificationException if the list is modified while replaceAll() is not finished.

2. ArrayList.replaceAll() Example

The following Java programs use replaceAll() method to change all list items to lowercase using a lambda expression.

2.1. Using Inline Expression

We can use the inline lambda expressions in case we have to execute only a single statement.

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 Implementation of UnaryOperator

Create a new class that implements UnaryOperator to execute a more complex logic on each element of the arraylist.

class MyOperator implements UnaryOperator<String> {

  @Override
  public String apply(String t) {

    //Add your custom logic here
    return t.toLowerCase();
  }
}

Now we can use the MyOperator as follows:

ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
System.out.println(alphabets);
 
alphabets.replaceAll( new MyOperator() );  
System.out.println(alphabets);

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: ArrayList Java Docs

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode