Collections replaceAll method

In this post under Java Collections, I will explain with example the purpose of Collections “replaceAll” method.

This method replaces all occurrences of a particular element with its replacements.

This method can be used only with “List” data structure.

Below is the main class showing an example

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.Collections;
5  import java.util.List;
6  
7  public class ListReplaceAllDemo {
8      public static void main(String[] args) {
9          List<Integer> integerList = new ArrayList<>(0);
10         integerList.add(1);
11         integerList.add(2);
12         integerList.add(2);
13         integerList.add(3);
14         integerList.add(3);
15         integerList.add(3);
16 
17         System.out.println("Before replacing: " + integerList);
18 
19         Collections.replaceAll(integerList, 2, 5);
20 
21         System.out.println("After replacing: " + integerList);
22     }
23 }

In the above code, at line 9 I create a list of element type “Integer”.

From line 10 to 15, I populate it with integer elements.

At line 19, I call “Collections” static “replaceAll” method. It take 3 arguments which are
1) the list
2) the item which has to be replaced
3) the item which has to be added

In our example, I am searching for all occurrences of 2 and replacing it with 5.

In this way we can use “replaceAll” method.

Leave a comment