How to find the number of (key , value) pairs in a map in scala?

Tanvi picture Tanvi · Jul 25, 2014 · Viewed 17.1k times · Source

I need to find the number of (key , value) pairs in a Map in my Scala code. I can iterate through the map and get an answer but I wanted to know if there is any direct function for this purpose or not.

Answer

Govind Singh picture Govind Singh · Jul 25, 2014

you can use .size

scala> val m=Map("a"->1,"b"->2,"c"->3)
m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> m.size
res3: Int = 3