Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaCopyOnArrayList replaceAll() method in Java with Examples

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:




// 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");
    }
}


Output:

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

Most Popular

Recent Comments