Comparing two collections for equality

In this post under Apache Collections, I will show with example how to compare two collections for equality.

We consider two collections are equal if they have same elements repeated same number of times.

The Apache Collections tool has “isEqualCollection” method on “CollectionUtils” class which we can use to compare two collections for equality.

Below is the complete code for your reference.

Main class

1  package defaultPackage;
2  
3  import org.apache.commons.collections4.CollectionUtils;
4  
5  import java.util.ArrayList;
6  import java.util.List;
7  
8  public class Example12 {
9      public static void main(String[] args) {
10         List<Integer> list1 = new ArrayList<>(0);
11         list1.add(1);
12         list1.add(1);
13         list1.add(2);
14         list1.add(3);
15 
16         List<Integer> list2 = new ArrayList<>(0);
17         list2.add(1);
18         list2.add(1);
19         list2.add(3);
20         list2.add(2);
21 
22         List<Integer> list3 = new ArrayList<>(0);
23         list3.add(1);
24         list3.add(2);
25         list3.add(3);
26 
27         System.out.println("list1 compared with list2 for equality: " + CollectionUtils.isEqualCollection(list1, list2));
28         System.out.println("list2 compared with list3 for equality: " + CollectionUtils.isEqualCollection(list2, list3));
29     }
30 }

In the above code, at line 10, 16, and 22, I have created 3 lists “list1”, “list2”, and “list3”. These lists will hold elements of type Integer.

I have then populated these lists with integer values.

Then at line 27, I compare “list1” with “list2”. Since both of them have same number of elements repeated same number of times. They are equal.

Then at line 28, I compare “list2” with “list3”. Both of them have same number of elements but they are not repeated same number of times. So they are not equal.

Below is the output

Output

list1 compared with list2 for equality: true
list2 compared with list3 for equality: false

In this way we can compare two collections for equality.

Leave a comment