
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this tutorial, we’ll see how can we find unique items in a list using Scala.
The first approach we have is by making use of List.distinct method, which will return all elements, without duplicates:
scala> List(1,3,2,2,1).distinct
val res0: List[Int] = List(1, 3, 2)
We can also just convert the list into a set if we don’t care about preserving order:
scala> List(1,3,2,2,1).toSet
val res1: Set[Int] = Set(1, 3, 2)
But if we’re dealing with more complex objects, where equality is not straightforward, we can use List.distinctBy, which allows specifying a comparison function:
scala> List(("a", 2.7), ("b", 2.1), ("a", 5.4)).distinctBy(_._2.floor)
val res2: List[(String, Double)] = List((a,2.7), (a,5.4))
We should take into account that there’s no guarantee regarding which of the “duplicates” is returned. For our example, it returned the first one, but the behavior is not specified in the API and can change depending on the environment and version.
In this article, we saw a few different ways to find unique items in a list using Scala.