Scala: How to check if all items are unique in a Seq?

不想你离开。 提交于 2019-12-13 17:04:58

问题


Is there a more idiomatic and maybe faster way to check if there are duplicates in a Seq, than this:

mySeq.size == mySeq.toSet.size

回答1:


This will be faster, because it can terminate early:

def allUnique[A](to: TraversableOnce[A]) = {
  val set = scala.collection.mutable.Set[A]()
  to.forall { x =>
    if (set(x)) false else {
      set += x
      true
    }
  }
}


来源:https://stackoverflow.com/questions/23752677/scala-how-to-check-if-all-items-are-unique-in-a-seq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!