Way2Java

Java Replace elements with replaceAll()

The replaceAll() method of Collections algorithms is useful to replace an element in the list. The element may appear any number of times in the list and in all the places it is replaced with the new value.

Following is the method signature

Example on Java Replace elements with replaceAll()
import java.util.*;
public class CollectionsReplaceAll
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(10);      
    myList.add(20);
    myList.add(10);      
    myList.add(40);
    System.out.println("Elements myList before replacing: " + myList);

    boolean success = Collections.replaceAll(myList, 10, 100);
    System.out.println("Replace operation successful: " + success);
    System.out.println("Elements myList after replacing: " + myList);

    success = Collections.replaceAll(myList, 50, 200);
    System.out.println("\nReplace operation successful: " + success);
  }
}



Output screenshot onfJava Replace elements with replaceAll()

ArrayList myList = new ArrayList();
myList.add(10); myList.add(20);
myList.add(10); myList.add(40);

An ArrayList myList is created and added 10, 20 and 40 elements where 10 is repeated twice.

boolean success = Collections.replaceAll(myList, 10, 100);
System.out.println(“Replace operation successful: ” + success);

In the above code, all the occurrences of 10 are replaced with 100 in myList. As the element 10 is found and the operation is successful, the method replaceAll() returns true and is printed.

success = Collections.replaceAll(myList, 50, 200);
System.out.println(“\nReplace operation successful: ” + success);

Now the replace operation is done on the element with value 50 which does not exist at all in myList. As the operation is failure, the method returns false and is printed.