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
Scala Map count() method with exampleThe count() method is utilized to count pair of keys in the Map. Return Type: It returns the number of keys present in the map that satisfies the given predicate. So, the identical keys are counted only once.
Scala Stack count() method with example In Scala Stack class , the count() method is utilized to count the number of elements in the stack that satisfies a given predicate. Return Type: It returns the count the number of elements in the stack that satisfies a given predicate.
mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With