检查集合中包含的所有元组中的给定元素是否相等

Checking if a given element in all the tuples contained in the collection is equal

提问人:Krzysztof Słowiński 提问时间:6/20/2019 最后编辑:Krzysztof Słowiński 更新时间:6/20/2019 访问量:84

问:

有一个元组集合,我想检查所有元组中的给定元素是否相等。

例如,考虑此数组中所有元组的第二个元素应返回:false

val a = Array((4,2), (8,1), (9,4), (10,2), (13,1))

在考虑此数组中所有元组的第二个元素时,应返回:true

val b = Array((4,3), (8,3), (9,3), (10,3), (13,3))
Scala 集合 元组相

评论


答:

6赞 Gal Naor 6/20/2019 #1

如果我正确理解了你的问题,你可以这样做:

val a = Array((4,2), (8,1), (9,4), (10,2), (13,1))
val b = Array((4,3), (8,3), (9,3), (10,3), (13,3))

a.map(_._2).toSet.size == 1 // false
b.map(_._2).toSet.size == 1 // true

你可以在这里玩它

3赞 Mario Galic 6/20/2019 #2

尝试

a.forall { case (key, value) => value == a.head._2 } // res2: Boolean = false
b.forall { case (key, value) => value == b.head._2 } // res3: Boolean = true

请注意,在空数组的情况下,此解决方案返回 。Array.empty[(Int, Int)]true

灵感来自 https://stackoverflow.com/a/41478838/5205022