Suppose I have
val dirty = List("a", "b", "a", "c")
Is there a list operation that returns "a", "b", "c"
Remove duplicates from list using Set. To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of set() method is that it returns distinct elements.
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.
scala.collection.immutable.List
now has a .distinct
method.
So calling dirty.distinct
is now possible without converting to a Set
or Seq
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With