Scala how can I count the number of occurrences in a list
val list = List(1,2,4,2,4,7,3,2,4)
I want to implement it like this: list.count(2)
(returns 3).
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")
scala collections do have count
: list.count(_ == 2)
I had the same problem as Sharath Prabhal, and I got another (to me clearer) solution :
val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(l => l).map(t => (t._1, t._2.length))
With as result :
Map(banana -> 1, oranges -> 3, apple -> 3)
list.groupBy(i=>i).mapValues(_.size)
gives
Map[Int, Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)
Note that you can replace (i=>i)
with built in identity
function:
list.groupBy(identity).mapValues(_.size)