Grundlefleck Grundlefleck - 1 year ago 116
Java Question

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

What is the simplest way to find if two Lists contain exactly the same elements, in the standard Java libraries?

It shouldn't matter if the two Lists are the same instance or not, and it shouldn't matter if the type parameter of the Lists are different.


List list1
List<String> list2;
// ... construct etc

// the function, given these two lists, should return true

There's probably something staring me in the face I know :-)

EDIT: To clarify, I was looking for the EXACT same elements and number of elements, in order.

EDIT: Thanks for pointing out the obvious answer I couldn't see for looking :-)

Although all the answers given so far are correct, some are more correct than others, so I'll wait a while for the best rounded-off answer before accepting.

Answer Source

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


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 listEqualsNoOrder(List<T> l1, List<T> l2) {
    final Set<T> s1 = new HashSet<>(l1);
    final Set<T> s2 = new HashSet<>(l2);

    return s1.equals(s2);

One caveat with this approach is that it won't check duplicates exactly. eg: if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would say they were equal.

If you don't want these to be treated as equal but you don't care about order you can either sort both lists before comparing them or you could do the same thing as the Set approach but with a Multiset (not part of the standard libraries, but Google Guava has a good one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download