In Scala how do I remove duplicates from a list?
Solution 1:
Have a look at the ScalaDoc for Seq,
scala> dirty.distinct
res0: List[java.lang.String] = List(a, b, c)
Update. Others have suggested using Set
rather than List
. That's fine, but be aware that by default, the Set
interface doesn't preserve element order. You may want to use a Set implementation that explicitly does preserve order, such as collection.mutable.LinkedHashSet.
Solution 2:
scala.collection.immutable.List
now has a .distinct
method.
So calling dirty.distinct
is now possible without converting to a Set
or Seq
.
Solution 3:
Before using Kitpon's solution, think about using a Set
rather than a List
, it ensures each element is unique.
As most list operations (foreach
, map
, filter
, ...) are the same for sets and lists, changing collection could be very easy in the code.