Java Replace elements with replaceAll()

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

  • static boolean replaceAll(List list1, Object oldObj, Object newObj): Replaces the old element oldObj with the new element newObj in the List list1 (all the occurrences). Returns true when the operation is successful (when the oldObj exists).
Example on Java Replace elements with replaceAll()


Java Replace elements with replaceAll()
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.

Leave a Reply

Your email address will not be published. Required fields are marked *