30

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Tanvi
  • 413
  • 1
  • 5
  • 14
  • 2
    You might find it helpful to spend some time looking at the [Scala Collections API](http://www.scala-lang.org/docu/files/collections-api/collections.html) document and trying things out in the REPL. Having a working knowledge of what you can do with collections will help you tackle a lot of problems. – AmigoNico Jul 26 '14 at 21:13

2 Answers2

40

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
Govind Singh
  • 15,282
  • 14
  • 72
  • 106
7

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220