3

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
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
muhuk
  • 15,777
  • 9
  • 59
  • 98
  • Nope, other than writing your own implicits. See similar question here: http://stackoverflow.com/questions/7691971/easiest-way-to-decide-if-list-contains-duplicates – Akos Krivachy May 20 '14 at 06:50

1 Answers1

3

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
    }
  }
}
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52