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

醉酒当歌 提交于 2019-12-05 08:47:47

问题


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.


回答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



回答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.



来源:https://stackoverflow.com/questions/24952447/how-to-find-the-number-of-key-value-pairs-in-a-map-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!