Compare two ArrayList in Java

We often need to compare two ArrayList in Java. In this post, you will learn how to do that in two ways:

  • Using the ArrayList.equals() method
  • Using the CollectionUtils.isEqualCollection() method

Compare two ArrayList in Java using the ArrayList.equals() method

The ArrayList.equals() method compares two ArrayList. It compares the sizes of the lists, elements equality, and the order of elements.

Example

class Test {

  public static void main(String[] args) {
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

    // list2 is equal to list1
    List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

    // list3 has the same elements but in diff order
    List<Integer> list3 = new ArrayList<>(Arrays.asList(3, 1, 4, 2));

    System.out.println("list1 == list2: " + list1.equals(list2));
    System.out.println("list1 == list3: " + list1.equals(list3));
  }
}
Output: list1 == list2: true list1 == list3: false

Using the CollectionUtils.isEqualCollection() method

If you do not care about the order of elements, then you can use the isEqualCollection() method from the CollectionUtils class that belongs to the Apache Commons library.

Note: If you are using a Maven project, add this to the pom.xml:

  <dependency>
    <groupid>org.apache.commons</groupid>
    <artifactid>commons-collections4</artifactid>
    <version>4.4</version>
 </dependency>

Example

class Test {

  public static void main(String[] args) {
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

    // list2 is equal to list 2
    List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

    // list3 has the same elements but in diff order
    List<Integer> list3 = new ArrayList<>(Arrays.asList(3, 1, 4, 2));

    // list4 is not the same
    List<Integer> list4 = new ArrayList<>(Arrays.asList(3, 7, 9, 2));

    System.out.println("list1 == list2: " + CollectionUtils.isEqualCollection(list1, list2));
    System.out.println("list1 == list3: " + CollectionUtils.isEqualCollection(list1, list3));
    System.out.println("list1 == list4: " + CollectionUtils.isEqualCollection(list1, list4));
  }
}
Output: list1 == list2: true list1 == list3: true list1 == list4: false
 
That’s it.
 
Happy coding!

Leave a Reply

Your email address will not be published.