Is there a way to check if two Collections contain

2019-01-09 00:40发布

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.

3条回答
一纸荒年 Trace。
2楼-- · 2019-01-09 00:56

If you want to ignore order, then how about testing sets for equality?

new HashSet(c1).equals(new HashSet(c2))
查看更多
Fickle 薄情
3楼-- · 2019-01-09 01:01

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.

查看更多
叛逆
4楼-- · 2019-01-09 01:04

This is three method calls and uses Google CollectionsGuava, but is possibly as simple as it gets:

HashMultiset.create(c1).equals(HashMultiset.create(c2));

Creating the temporary Multisets may appear wasteful, but to compare the collections efficiently you need to index them somehow.

查看更多
登录 后发表回答