[英]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. 我一直在寻找一个像Arrays.equals(a1, a2)
一样操作的方法,但忽略了元素顺序。 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 Iterable
s, but I'm also fine with simply taking Collection
s Such a method would of course take into account any duplicate elements in the collection (so it can't simply test for containsAll()
). 我无法在任何Google Collections中找到它(类似于Iterables.elementsEqual()
,但确实考虑了排序)和JUnit( assertEquals()
显然只是在Collection上调用equals()
,这取决于Collection实现,这不是我想要的)最好是这样的方法会采用Iterable
,但我也可以简单地使用Collection
s这样的方法当然会考虑Collection
的任何重复元素(所以它不能简单地测试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库都有它。
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. 如果给定的集合包含具有完全相同基数的完全相同的元素,则返回true。
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. 也就是说,如果a中的e的基数等于b中的e的基数,则对于a或b中的每个元素e。
Which is, I think, exactly what you're after. 我认为,这正是你所追求的。
This is three method calls and uses Google Collections Guava , but is possibly as simple as it gets: 这是三个方法调用并使用Google Collections Guava ,但可能很简单:
HashMultiset.create(c1).equals(HashMultiset.create(c2));
Creating the temporary Multiset
s may appear wasteful, but to compare the collections efficiently you need to index them somehow. 创建临时Multiset
可能看起来很浪费,但要有效地比较集合,您需要以某种方式索引它们。
如果你想忽略秩序,那么如何测试集合是否相等?
new HashSet(c1).equals(new HashSet(c2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.