Editors Top

We’re looking for a new Scala technical editor to help review new articles for the site.

1. Overview

In this tutorial, we’ll see how can we find unique items in a list using Scala.

2. Find Unique Items in a List

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.

3. Conclusion

In this article, we saw a few different ways to find unique items in a list using Scala.

Comments are closed on this article!