How to check if two lists are equal in Java

This short article will explain to you what List equality means and how to compare two Java lists against each other.

Introduction

Checking list equality is a widespread problem; we often need to compare the list elements against each other. Comparison and assertion occur many times during the testing when we need to assert results with predefined expectations.

Two lists equality

At first, some might think, that for equality of two lists is conditioned by lists containing the same elements. This way of thinking is not entirely true. Single look into the Java documentations for List.equals() method will uncover us true meaning of list equality:

… two lists are defined to be equal if they contain the same elements in the same order.

Therefore, we need to compare the lists’ elements mutually, but we also need to check the order of the elements in the lists reciprocally.

So first, let’s take a good look at how not to do a list equality check.

Compare two list with the bruteforce

Following lines of code are placed here only for demonstration purposes. For all cost, you must avoid such hideous brute force solution in your code.

private boolean compareLists(final List list1,final List list2) {
    if(list1.size() == list2.size()) {
        if(list1.isEmpty() && list2.isEmpty()) {
            return true;
        }
        for(int i = 0; i < list1.size(); i++) {
            if(!list1.get(i).equals(list2.get(i))) {
                return false;
            };
        }
        return true;
    }
    return false;
}

The reason why to not use it in your code is that this code is basically List interface implementation of the equal() method. Therefore all you need to use for comparing two lists is to call equal() method.

private boolean compareLists(final List list1,final List list2) {
    return list1.equals(list2);
}

Interface method definition ensures that the equals method works through different implementations of the List interface in a same way.

Framework usage

For testing purposes, it is probably better to use some of the available Java frameworks for testing, which can give us more options in List testing.

In our examples, we will play with the following code snippet based on user entities belonging to different groups. We will compare lists are figure out if all users are members of all groups.

List users = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");
List moderators = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");
List admins = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");

JUnit

Rather than using and printing equals for tests, it is better to use assert methods. JUnit testing framework offers us three suitable ways for list equality assertion.

  • assertEquals(expected, actual) - Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null, they are considered equal.
  • assertNotSame(unexpected, actual) - Asserts that two objects do not refer to the same object. If they do refer to the same object, an AssertionError without a message is thrown.
  • assertNotEquals(unexpected, actual) - Asserts that two objects are not equals. If they are, an AssertionError without a message is thrown. If unexpected and actual are null, they are considered equal.
@Test
public void testJUnitListAsserts() throws Exception {
    Assert.assertEquals(users, moderators);
    Assert.assertNotSame(users, moderators);
    Assert.assertNotEquals(users, admins);
}

Conclusion

This article has shown you how not to do list assertion and explain how to check and assert two lists equality.

As always, you can find all our examples on our GitHub project!

This entry was posted in Testing and tagged , , , , . Bookmark the permalink.

Leave a Reply

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

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