CopyOnArrayList replaceAll() method in Java with Examples

The java.util.concurrent.CopyOnArrayList.replaceAll() method in Java replaces each element of this list with the result of applying the operator to the element.

Syntax:

 public void replaceAll(UnaryOperator operator)

Parameters: This method accepts a mandatory parameter operator which is to be applied to each element.



Return Type: This method has no return value.

Below Programs illustrate the replaceAll() method of CopyOnArrayList in Java:

Program 1: This program involves CopyOnArraylist replaceAll() method of String Type:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to illustrate CopyOnArrayList
// replaceAll() method
  
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
import java.util.function.UnaryOperator;
  
public class GFG {
    public static void main(String[] args)
    {
        CopyOnWriteArrayList<String> ArrLis1
            = new CopyOnWriteArrayList<String>();
  
        // Add elements
        ArrLis1.add("White");
  
        ArrLis1.add("Red");
  
        ArrLis1.add("Blue");
  
        ArrLis1.add("Green");
  
        // print CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: "
                           + ArrLis1);
  
        // check using function
        ArrLis1.replaceAll(new MyOperator());
  
        // print CopyOnWriteArrayList
        System.out.println("After replacement CopyonWriteArrayList: "
                           + ArrLis1);
    }
}
  
class MyOperator implements UnaryOperator<String> {
    public String apply(String t)
    {
        return t.replaceAll("Red", "White");
    }
}

chevron_right


Output:

CopyOnWriteArrayList: [White, Red, Blue, Green]
After replacement CopyonWriteArrayList: [White, White, Blue, Green]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.