How in Scala to find unique items in List?
If you refer to the Rosetta Code: Create a Sequence of unique elements
val list = List(1,2,3,4,2,3,4,99)
val l2 = list.removeDuplicates
// l2: scala.List[scala.Int] = List(1,2,3,4,99)
Since List
is immutable, you wont modify the initial List
by calling removeDuplicates
Warning: as mentioned by this tweet(!), this does not preserve the order:
scala> val list = List(2,1,2,4,2,9,3)
list: List[Int] = List(2, 1, 2, 4, 2, 9, 3)
scala> val l2 = list.removeDuplicates
l2: List[Int] = List(1, 4, 2, 9, 3)
For a Seq
, that method should be available in Scala2.8, according to ticket 929.
In the meantime, you will need to define an ad-hoc static method as the one seen here
In 2.8, it's:
List(1,2,3,2,1).distinct // => List(1, 2, 3)