Authors Top

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this tutorial, we’ll see how we can count the number of occurrences of an element in a Scala List.

2. Count the Number of Occurrences in a List

Here’s the list we’ll be working with:

scala> val lst = List('a', 'b', 'b', 'c', 'a', 'b', 'd', 'e', 'e', 'e', 'a', 'a')
val lst: List[Char] = List(a, b, b, c, a, b, d, e, e, e, a, a)

There are multiple ways to count the number of occurrences in a List. Let’s look at them next.

2.1. Using the groupBy() method

The first solution we’ll look at is a naive approach. Given a List, we can group all elements by any function. For our goal, we can use the identity function. It’s a function that returns the exact same element that we passed as an argument. By using it in the .groupBy() method, we can build a list of repeated elements:

scala> lst.groupBy(identity)
val res0: Map[Char, List[Char]] = HashMap(e -> List(e, e, e), a -> List(a, a, a, a), b -> List(b, b, b), c -> List(c), d -> List(d))

As we can see, the groupBy() method returns a Map, where each key contains a list of all the elements found in the initial List. Since we just want to count the number of occurrences, we can just map the values to the size of the List:

scala> lst.groupBy(identity).mapValues(_.size)
val res1: Map[Char, Int] = HashMap(e -> 3, a -> 4, b -> 3, c -> 1, d -> 1)

And now we can just access the Map to find the count of occurrences for any given element:

scala> val occurences = lst.groupBy(identity).mapValues(_.size)
val occurences: Map[Char, Int] = HashMap(e -> 3, a -> 4, b -> 3, c -> 1, d -> 1)

scala> occurences('a')
val res2: Int = 4

scala> occurences('b')
val res3: Int = 3

scala> occurences('c')
val res4: Int = 1

2.2.Using the Native count() Method

While the previous approach worked just fine, it’s a bit complex and had too much boilerplate. Fortunately, Scala offers a better solution using the count() method:

scala> lst.count(_ == 'a')
val res11: Int = 4

scala> lst.count(_ == 'b')
val res12: Int = 3

scala> lst.count(_ == 'c')
val res13: Int = 1

As we can see, this solution is much cleaner than the previous one.

3. Conclusion

In this article, we saw how to get the number of occurrences of a given element in a Scala List. We can either group the elements first, or use the built-in count() method.

Authors Bottom

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

guest
0 Comments
Inline Feedbacks
View all comments