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.
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With