Simple way to find if two different lists contain exactly the same elements?

If you care about order, then just use the equals method:

list1.equals(list2)

From the javadoc:

Compares the specified object with
this list for equality. Returns true
if and only if the specified object is
also a list, both lists have the same
size, and all corresponding pairs of
elements in the two lists are equal.
(Two elements e1 and e2 are equal if
(e1==null ? e2==null :
e1.equals(e2)).) In other words, two
lists are defined to be equal if they
contain the same elements in the same
order. This definition ensures that
the equals method works properly
across different implementations of
the List interface.

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was [“A”, “B”, “A”] and list2 was [“A”, “B”, “B”] the Set approach would consider them to be equal.

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

Leave a Comment