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:

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:

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():

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

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

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:

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.

Leave a Comment

Your email address will not be published. Required fields are marked *