How to find the number of (key , value) pairs in a map in scala?
17,803
Solution 1
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
Solution 2
Use Map#size
:
The size of this traversable or iterator.
The size
method is from TraversableOnce so, barring infinite sequences or sequences that shouldn't be iterated again, it can be used over a wide range - List, Map, Set, etc.
Author by
Tanvi
Updated on June 03, 2022Comments
-
Tanvi almost 2 years
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.