Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala count number of occurences of an element in a Map

Tags:

scala

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
like image 793
goo Avatar asked Jun 16 '14 07:06

goo


People also ask

How to get count of Map in scala?

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.

How to use count method in scala?

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.

What is Scala mapValues?

mapValues creates a Map with the same keys from this Map but transforming each key's value using the function f .


1 Answers

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.

like image 161
Ven Avatar answered Oct 27 '22 21:10

Ven