Scala - How to find the unique items in a List, Array, Vector (sequence)

Scala FAQ: How do I find the unique items in a List, Array, Vector, or other Scala sequence?

Solution: Use the distinct method.

Here's a simple example using a List of integers:

scala> val x = List(1,1,1,2,2,3,3)
x: List[Int] = List(1, 1, 1, 2, 2, 3, 3)

scala> x.distinct
res0: List[Int] = List(1, 2, 3)

As you can see, res0 now contains only the unique elements in the list.

Here's another example with a list of strings:

scala> val x = List("a", "a", "b", "b", "c")
x: List[String] = List(a, a, b, b, c)

scala> x.distinct
res1: List[String] = List(a, b, c)

Last but not least, here's a list of a custom type, a Person class defined as a case class:

scala> case class Person(name: String, age: Int)
defined class Person

scala> List(Person("joe",20), Person("fred",22), Person("joe", 20), Person("mary", 24)).distinct
res2: List[Person] = List(Person(joe,20), Person(fred,22), Person(mary,24))

scala> List(Person("joe",20), Person("fred",22), Person("joe", 20), Person("fred",22)).distinct
res3: List[Person] = List(Person(joe,20), Person(fred,22))

If you need to find the unique elements in a list/sequence in Scala, I hope this has been helpful.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.