Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 830
Tanvi Avatar asked Jul 25 '14 09:07

Tanvi


People also ask

How do you count keys on a map?

map count() function in C++ STL Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.

Is a collection of keys or value pairs in Scala?

Scala's Map is a collection of key-value pairs, where each key needs to be unique. Thanks to that, we have direct access to a value under a given key. Scala defines two kinds of maps, the immutable, which is used by default and mutable, which needs an import scala.

How do you get a key-value pair on a map?

To get the key and value elements, we should call the getKey() and getValue() methods. The Map. Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.

How do you check if a map contains a key in Scala?

Scala map contains() method with example It checks whether the stated map contains a binding for a key or not. Where, k is the key. Return Type: It returns true if there is a binding for the key in the map stated else returns false.


Video Answer


2 Answers

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 
like image 73
Govind Singh Avatar answered Sep 23 '22 19:09

Govind Singh


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.

like image 26
user2864740 Avatar answered Sep 22 '22 19:09

user2864740