是否有API方法可以比较Seq的内容而不考虑顺序? [英] Is there an API method that compares contents of a Seq irrespective of order?

查看:66
本文介绍了是否有API方法可以比较Seq的内容而不考虑顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

val l1 = List(1,2,3) 
val l2 = List(2,3,1)

我想要一种方法来确认l1等于l2(同上内容,但顺序不同)。列表/序列上是否有API方法可以做到这一点?

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

不能正常工作,因为它也可以验证订单。

does not work as it verifies order as well.

我已经提出以下内容:

l1.foldLeft(l1.size == l2.size)(_ && l2.contains(_))

进行上述比较是否比以上更简洁?

Is there anything more succinct than the above to do this comparison?

推荐答案

如果要的是这些列表包含相同的元素,而与顺序或重复无关:

If what you want is "these lists contain the same elements, irrespective of order or repetitions":

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

如果您想要的是这些列表包含相同的元素且大小相同,但是给定元素的重复次数在两个列表:

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

这篇关于是否有API方法可以比较Seq的内容而不考虑顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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