scala 是否有一种 API 方法可以不考虑顺序来比较 Seq 的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3622895/
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
Is there an API method that compares contents of a Seq irrespective of order?
提问by ssanj
Assuming:
假设:
val l1 = List(1,2,3)
val l2 = List(2,3,1)
I want a method that confirms that l1 is equal to l2 (as in same contents but different order). Is there an API method on List/Seq to do this?
我想要一种确认 l1 等于 l2 的方法(内容相同但顺序不同)。List/Seq 上是否有 API 方法可以执行此操作?
l1.sameElements(l2)
does not work as it verifies order as well.
不起作用,因为它也验证订单。
I've come up with the following:
我想出了以下几点:
l1.foldLeft(l1.size == l2.size)(_ && l2.contains(_))
Is there anything more succinct than the above to do this comparison?
有没有比上面更简洁的方法来做这个比较?
回答by Tom Crockett
If what you want is "these lists contain the same elements, irrespective of order or repetitions":
如果您想要的是“这些列表包含相同的元素,无论顺序或重复”:
l1.toSet == l2.toSet
l1.toSet == l2.toSet
If what you want is "these lists contain the same elements, and with the same number of repetitions of each":
如果您想要的是“这些列表包含相同的元素,并且每个元素的重复次数相同”:
l1.sorted == l2.sorted
l1.sorted == l2.sorted
If what you want is "these lists contain the same elements and are the same size, but the number of repetitions of a given element can differ between the two lists":
如果您想要的是“这些列表包含相同的元素并且大小相同,但是两个列表之间给定元素的重复次数可能不同”:
l1.size == l2.size && l1.toSet == l2.toSet
l1.size == l2.size && l1.toSet == l2.toSet
回答by Dave Griffith
While
尽管
l1.sorted == l2.sorted
is correct, it's runtime performance is O(n log n), because of the sorting. For large lists, you are probably better with
是正确的,由于排序,它的运行时性能是 O(n log n)。对于大型列表,您可能更适合
l1.groupBy(identity) == l2.groupBy(identity)
which should be O(n), assuming a decent implementation of groupBy.
假设 groupBy 的实现不错,这应该是 O(n)。

