Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if two Collections contain the same elements, independent of order?

I've been looking for a method that operates like Arrays.equals(a1, a2), but ignoring the element order. I haven't been able to find it in either Google Collections (something like Iterables.elementsEqual(), but that does account for ordering) and JUnit (assertEquals() obviously just calls equals() on the Collection, which depends on the Collection implementation, and that's not what I want) It would be best if such a method would take Iterables, but I'm also fine with simply taking Collections Such a method would of course take into account any duplicate elements in the collection (so it can't simply test for containsAll()).

Note that I'm not asking how to implement such a thing, I was just wondering if any of the standard Collections libraries have it.

like image 440
Jorn Avatar asked Oct 14 '09 09:10

Jorn


People also ask

Which collections method is used to check whether two collections have no elements in common?

The disjoint() method of Java Collections class is used to check whether two specified collections are disjoint or not. It returns true if the two specified collections have no elements in common.

How can you tell if two Arraylists have the same element?

You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.

How do you check if two elements in a list are the same Java?

List equals() Method in Java with Examples. This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal. Parameters: This function has a single parameter which is object to be compared for equality.


1 Answers

Apache commons-collections has CollectionUtils#isEqualCollection:

Returns true if the given Collections contain exactly the same elements with exactly the same cardinality.

That is, if the cardinality of e in a is equal to the cardinality of e in b, for each element e in a or b.

Which is, I think, exactly what you're after.

like image 123
Cowan Avatar answered Sep 21 '22 17:09

Cowan