Core Java

Check If Two Lists Are Equal In Java

Introduction:

Lists in Java are ordered by nature. So, two lists are considered to be equal if they contain the exact same elements in the same order. In this tutorial, we’ll see how to compare two Lists for equality in Java.

We’ll also cover ways in which we can just compare the elements in two lists and ignore their order.

Lists Equality Maintaining Order:

As we know, two lists are equal when they have exactly the same elements and in the exact same order. So if we care about the order, we can use equals() method for equality check:

Java

@Test
public void equalityCheckOfTwoLists() {
 
    List<Integer> list1 = Arrays.asList(1, 2, 3);
    List<Integer> list2 = Arrays.asList(1, 2, 3);
    List<Integer> list3 = Arrays.asList(2, 1, 3);
 
    assertTrue(list1.equals(list2));
    assertFalse(list1.equals(list3));
 
}

Both list1 and list3 contain the same elements {1, 2, 3} but in different orders and so are considered unequal.

Lists Equality Ignoring Order:

What if we wish to ignore the order of elements for the equality check?

Many a time all we want is to check if the two lists contain the same elements, irrespective of their order in the list. Let’s cover the ways to achieve it:

1. Sorting Lists And Comparing:

If both lists are null, we’ll return true. Or else if only one of them points to a null value or the size() of two lists differ, then we’ll return false. If none of those conditions holds true, we’ll first sort the two lists and then compare them:

Java

public <T extends Comparable<T>> boolean isEquals(List<T> list1, List<T> list2){     
    if (list1 == null && list2 == null) {
        return true;
    }
    //Only one of them is null
    else if(list1 == null || list2 == null) {
        return false;
    }
    else if(list1.size() != list2.size()) {
        return false; 
    }
    
    //copying to avoid rearranging original lists
    list1 = new ArrayList<T>(list1); 
    list2 = new ArrayList<T>(list2);   
 
    Collections.sort(list1);
    Collections.sort(list2);      
    
    return list1.equals(list2);
}

Note that we have created copies of the two lists to ensure that the elements in the original lists remain untouched.

2. With Sets / contains() Check:

If the data in our lists are unique i.e. there isn’t a duplication, we can simply create TreeSets from the given lists and then compare them using equals():

Java

public <T extends Comparable<T>> boolean isEquals(List<T> list1, List<T> list2){     
    if (list1 == null && list2 == null) {
        return true;
    }
    //Only one of them is null
    else if(list1 == null || list2 == null) {
        return false;
    }
    else if(list1.size() != list2.size()) {
        return false; 
    }
 
    Set<T> set1 = new TreeSet<>(list1);
    Set<T> set2 = new TreeSet<>(list2);
    
    return set1.equals(set2);
}

We can further simplify it by just having a contains() check, instead of creating the Sets:

Java

return list1.containsAll(list2) && list2.containsAll(list1);

However, note that these approaches (contains() check / With Sets) will fail in case we have repetitions in our data set. For instance:

Java

List<Integer> list1 = Arrays.asList(1, 2, 3, 3);
List<Integer> list2 = Arrays.asList(3, 1, 2, 2);
 
// will return true, but actual value should be false
System.out.println(list1.isEquals(list2));

In the above example, list1 contains one 2’s and two 3’s whereas list2 contains two 2’s and one 3’s. Still, this form of implementation will incorrectly return true.

3. Apache Commons:

Instead of writing our own code, we can rather choose the Apache Commons Collections utility to do the job:

Java

List<Integer> list1 = Arrays.asList(1, 2, 3, 3);
List<Integer> list2 = Arrays.asList(3, 1, 3, 2);
 
System.out.println(CollectionUtils.isEqualCollection(list1, list2)); //true

The isEqualCollection() method returns true when the two collections contain exact same elements with exactly the same cardinalities.

Conclusion:

In this tutorial, we learned to check if two lists are equals in Java. We now know the fact that, by default, the two lists are equals when they have the same elements in the same order.

We also discussed the approaches we can take for the lists equality check if we don’t care enough about the order of the elements.

Be the First to comment.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Check If Two Lists Are Equal In Java

Opinions expressed by Java Code Geeks contributors are their own.

Shubhra Srivastava

Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button