【问题标题】:Checking if a given element in all the tuples contained in the collection is equal检查集合中包含的所有元组中的给定元素是否相等
【发布时间】:2019-11-03 04:29:28
【问题描述】:

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

例如考虑到这个数组中所有元组的第二个元素应该返回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 collections tuples equality


    【解决方案1】:

    试试

    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

    【讨论】:

      【解决方案2】:

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

      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
      

      你可以玩here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-03
        • 1970-01-01
        • 1970-01-01
        • 2018-05-13
        • 2015-02-12
        • 2018-04-22
        • 2021-06-20
        相关资源
        最近更新 更多