Way to check if two Collections contain the same elements, independent of order?
Assuming you've defined equals and hashcode, here's one way. Not very efficient for large members.
- Check the # of elements in each. If they are not equal, you are done [not equal].
- Loop through Set1. Check if Set2 contains each element, if not you are done [not equal]. otherwise if you get through the whole set, you are equal
UPDATE: I didn't know about containsAll, which saves a lot of trouble and basically does that algorithm
int s1 = set1.size();
int s2 = set2.size();
if (s1 !=s2) return false;
return set1.containsAll(set2);
If you want data equality then correctly implement equals()
and hashCode()
and then you can use Collection.containsAll(...). Ofcourse, you need to make sure you call this only when both of your collections have the same number of elements otherwise you can just say they aren't equal.
Use the below expression.
set1.containsAll(set2) && set2.containsAll(set1)
Quoting from AbstractSet.equals(Object) javadoc:
Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
So it's sufficient to simply call set1.equals(set2)
. It will return true
if and only if the set contain the same elements (assuming that you have correctly defined equals
and hashCode
on the objects in the sets).