CollectionUtils removeAll method

In this post under Apache Collections, I will explain with example the purpose of “CollectionUtils” class “removeAll” method.

This method takes two collections i.e, “collection1” and “collection2” as an arguments.

This method searches for elements in “collection2” in “collection1”. If the element is found in “collection1”, it is removed.

Basically, it returns a collection say “output” where

output = collection1 – collection2

Below is the complete main code for example.

Main class

1  package defaultPackage;
2  
3  import org.apache.commons.collections4.CollectionUtils;
4  
5  import java.util.ArrayList;
6  import java.util.Collection;
7  import java.util.List;
8  
9  public class Example14 {
10     public static void main(String[] args) {
11         List<Integer> inputList = new ArrayList<>(0);
12         inputList.add(1);
13         inputList.add(2);
14         inputList.add(3);
15         inputList.add(4);
16 
17         List<Integer> evenInputList = new ArrayList<>(0);
18         evenInputList.add(2);
19         evenInputList.add(4);
20 
21         List<Integer> oddInputList = new ArrayList<>(0);
22         oddInputList.add(1);
23         oddInputList.add(3);
24 
25         List<Integer> outputList = (List<Integer>)CollectionUtils.removeAll(inputList, evenInputList);
26         System.out.println(outputList);
27 
28         outputList = (List<Integer>)CollectionUtils.removeAll(inputList, oddInputList);
29         System.out.println(outputList);
30     }
31 }

In the above code, at line 11, I create an integer list named “inputList” and populate it in subsequent lines

At line 17, I create another integer list “evenInputList”, which contains only even numbers

At line 21, I create another integer list “oddInputList”, which contains only odd numbers.

At line 25, I call “removeAll” method and pass “inputList” and “evenInputList” as arguments.

The return value is collection which is equal to inputList – evenInputList.

At line 28, I call “removeAll” method again and pass “inputList” and “oddInputList” as arguments.

The return value is a collection which is equal to inputList – oddInputList.

In this way we can use “removeAll” method of “CollectionUtils” class.

Below is the output for reference

Output

[1, 3]
[2, 4]

Leave a comment