Java 有没有办法检查两个集合是否包含相同的元素,而与顺序无关?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1565214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:09:23  来源:igfitidea点击:

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

javacollectionsequals

提问by Jorn

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()).

我一直在寻找一种操作类似于 的方法Arrays.equals(a1, a2),但忽略了元素顺序。我无法在 Google Collections(类似于Iterables.elementsEqual(),但这确实说明排序)和 JUnit(assertEquals()显然只是调用equals()Collection,这取决于 Collection 实现,这不是我想要的)中找到它如果这样的方法需要Iterables最好,但我也可以简单地采用Collections 这样的方法当然会考虑集合中的任何重复元素(因此它不能简单地测试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.

请注意,我不是在问如何实现这样的东西,我只是想知道是否有任何标准的 Collections 库有它。

采纳答案by Cowan

Apache commons-collections has CollectionUtils#isEqualCollection:

Apache commons-collections 有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.

如果给定的 Collections 包含具有完全相同基数的完全相同的元素,则返回 true。

也就是说,如果 a 中 e 的基数等于 b 中 e 的基数,则对于 a 或 b 中的每个元素 e。

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

我认为,这正是您所追求的。

回答by newacct

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

如果你想忽略顺序,那么测试集是否相等呢?

new HashSet(c1).equals(new HashSet(c2))

回答by finnw

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

这是三个方法调用并使用Google Collections Guava,但可能很简单:

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.

创建临时Multisets 可能看起来很浪费,但要有效地比较集合,您需要以某种方式索引它们。