有没有办法检查两个集合是否包含相同的元素,而与顺序无关? [英] Is there a way to check if two Collections contain the same elements, independent of order?

查看:21
本文介绍了有没有办法检查两个集合是否包含相同的元素,而与顺序无关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

Apache commons-collections 有 CollectionUtils#isEqualCollection:

Apache commons-collections has CollectionUtils#isEqualCollection:

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

Returns true if the given Collections contain exactly the same elements with exactly the same cardinality.

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

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.

这篇关于有没有办法检查两个集合是否包含相同的元素,而与顺序无关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆