Scala Map: Find the size of a map
Scala Map Exercise-3 with Solution
Write a Scala program to create a map and find the size of the map.
Sample Solution:
Scala Code:
object MapSizeExample {
def main(args: Array[String]): Unit = {
// Create a map
val color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
// Print the map
println("Map: " + color_map)
// Find the size of the map
val map_size = color_map.size
// Print the size
println("Size of the map: " + map_size)
}
}
Sample Output:
Map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4) Size of the map: 4
Explanation:
In the above exercise -
- First we create a map "color_map" using the Map constructor and provide key-value pairs.
- To find the size of the map, we use the size method, which returns the number of key-value pairs in the map. We store the result in the "map_size" variable.
- Finally, we print the size using println.
Scala Code Editor :
Previous: Check if a map is empty.
Next: Retrieving values by key.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/map/scala-map-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics