Scala使用toSet.toList vs distinct

Sou*_*nta 9 collections scala list set distinct

如果我想获得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)
Run Code Online (Sandbox Code Playgroud)

whe*_*ies 7

直接从这里找到的源代码中获取:

/** 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
  }
Run Code Online (Sandbox Code Playgroud)

所以看来,如果订单保存很重要,distinct否则使用,它们相对同样昂贵.

  • 它根据定义在单个线程上执行的计算.它使用的可变集在此方法之外无法观察到.它积累的副作用与使用不可变结构和纯函数式编程提供的任何优点无关.最后,与使用不可变累加器集写入时相比,它几乎肯定是显着的(在真正意义上的单词,而不是"基本上"的同义词). (9认同)