goo
goo

Reputation: 2280

Scala count number of occurences of an element in a Map

How would I count the number of occurrences of an element in a Map?

example

val myMap = Map("word1" -> "foo", "word3" -> "word4", "word5" -> "foo")

myMap contains "foo" count //???
// returns 2

Upvotes: 6

Views: 7406

Answers (3)

elm
elm

Reputation: 20435

Yet another way,

myMap.values.filter { _ == "foo" }.size

Upvotes: 0

pagoda_5b
pagoda_5b

Reputation: 7383

In general, if you want to count occurences in a Map you can group by values and then transform the grouped submappings getting their size

scala> val occurrences = myMap groupBy ( _._2 ) mapValues ( _.size )
occurrences: scala.collection.immutable.Map[String,Int] = Map(word4 -> 1, foo -> 2)

This is handy if you need to have counts for every entry, and not only a single value. Otherwise @Ven's solution is more efficient

Upvotes: 4

Ven
Ven

Reputation: 19040

You can just use count with a predicate :

myMap.count({ case (k, v) => v == "word1" })

Alternatively:

myMap.values.count(_ == "word1")

Or even:

myMap.count(_._2 == "word1") // _2 is the second tuple element

Note: That's for values, not keys. Keys are unique.

Upvotes: 13

Related Questions