Scala how can I count the number of occurrences in a list

Gatspy picture Gatspy · Jul 12, 2012 · Viewed 120.9k times · Source
val list = List(1,2,4,2,4,7,3,2,4)

I want to implement it like this: list.count(2) (returns 3).

Answer

ohruunuruus picture ohruunuruus · Feb 13, 2015

A somewhat cleaner version of one of the other answers is:

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")

s.groupBy(identity).mapValues(_.size)

giving a Map with a count for each item in the original sequence:

Map(banana -> 1, oranges -> 3, apple -> 3)

The question asks how to find the count of a specific item. With this approach, the solution would require mapping the desired element to its count value as follows:

s.groupBy(identity).mapValues(_.size)("apple")