问题
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