【问题标题】:Scala using toSet.toList vs distinctScala 使用 toSet.toList vs distinct
【发布时间】:2014-05-08 20:49:48
【问题描述】:

如果我想获取 List 中的唯一元素,我可以执行 distinct 或调用 toSet.toList。哪个更有效,为什么?还有其他有效的方法吗?我的理解是distinct 也将保持顺序,而toSet.toList 不会。

scala> val mylist = List(1,2,3,3,4,4,4,5,6,6,6,6,7)
mylist: List[Int] = List(1, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 6, 7)

scala> mylist.distinct
res11: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

scala> mylist.toSet.toList
res12: List[Int] = List(5, 1, 6, 2, 7, 3, 4)

【问题讨论】:

    标签: list scala collections set distinct


    【解决方案1】:

    直接取自here找到的源代码:

    /** Builds a new $coll from this $coll without any duplicate elements.
    * $willNotTerminateInf
    *
    * @return A new $coll which contains the first occurrence of every element of this $coll.
    */
      def distinct: Repr = {
        val b = newBuilder
        val seen = mutable.HashSet[A]()
        for (x <- this) {
          if (!seen(x)) {
            b += x
            seen += x
          }
        }
        b.result
      }
    

    因此,如果订单保存很重要,请使用distinct,否则,它们相对来说同样昂贵。

    【讨论】:

    • 附带说明,“distinct”实现不起作用,并且使用可变状态和 val。有什么理由会这样吗?
    • 根据定义,它执行的计算是在单个线程上进行的。在此方法之外无法观察到它使用的可变集。它累积的副作用与使用不可变结构和纯函数式编程提供的任何优势无关。最后,几乎可以肯定,它比使用不可变累加器集编写的速度要快得多(真正意义上的,而不是“实质上”的同义词)。
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2018-09-29
    • 2013-08-17
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多