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

China☆狼群 提交于 2019-11-27 07:47:12
Cowan

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.

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.

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

new HashSet(c1).equals(new HashSet(c2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!