Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala how do I remove duplicates from a list?

Tags:

scala

Suppose I have

val dirty = List("a", "b", "a", "c") 

Is there a list operation that returns "a", "b", "c"

like image 501
deltanovember Avatar asked Aug 21 '11 00:08

deltanovember


People also ask

Which is used for removing duplicate elements from list?

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.


2 Answers

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.

like image 164
Kipton Barros Avatar answered Sep 17 '22 05:09

Kipton Barros


scala.collection.immutable.List now has a .distinct method.

So calling dirty.distinct is now possible without converting to a Set or Seq.

like image 23
crockpotveggies Avatar answered Sep 19 '22 05:09

crockpotveggies