This post will discuss how to compare two lists for equality in Java, ignoring the order. The List may be a List of primitive types or a List of Objects. Two lists are defined to be equal if they contain exactly the same elements in equal quantity each, in any order.

For example, [1, 2, 3] and [2, 1, 3] are considered equal, while [1, 2, 3] and [2, 4, 3] are not. The elements’ count also matters, hence, [1, 2, 3, 1] and [2, 1, 3, 2] are not treated equally. If the elements count doesn’t matter, you can convert both lists to a Set and compare them using the .equals() method of the Set interface.

1. Sorting

A simple solution is to sort both lists and then compare them using the .equals() method of the List interface. Note that this solution is not linear, and has O(n.log(n)) time complexity. It is not suitable for large lists.

To improve efficiency, it is recommended to first check if both lists have the same size or not. Also before sorting both lists, create their copy to avoid destroying the original order of both lists. Both copying and sorting steps can be done efficiently using Streams API, as shown below.

Download  Run Code

Output:

Both lists are equal

2. Using Multiset

Another solution is to convert both lists to multiset and compare the multiset, which compares elements regardless of their order and also preserves the count of duplicate elements. The following solution demonstrates this using Guava’s Multiset.

Download Code

Output:

Both lists are not equal

3. Apache Commons Lang Library

Finally, Apache Commons Lang Library offers the CollectionUtils.isEqualCollection() method, which returns true if the given Collections contain exactly the same elements with exactly the same cardinalities.

Download Code

Output:

Both lists are equal

4. Check equality in List of objects

To compare two lists of objects using any of the above methods, you need to override equals and hashCode methods for that object in Java. The following program demonstrates it:

Download Code

Output:

Both lists are equal

That’s all about comparing two lists for equality in Java, ignoring the order.