What is the map.size function in Scala?

The map.size function in Scala returns the number of elements (key-value pairs) in the map. In short, this function is used to get the current size of the map.

Figure 1 shows the visual representation of the map.size function.

Figure 1: Visual representation of map.size function

The following module is required in order to use the function: scala.collection.mutable.Map

Syntax

map_name.size
// where the map_name is the name of the map

Parameter

This function does not require a parameter.

Return value

This function returns the number of elements in the map and is used to get the current size of the map.

Example

The following code shows how to use map.size function in Scala.

import scala.collection.mutable.Map
object Main extends App {
//creating map with values
val map_1 = scala.collection.mutable.Map(
1 -> "Tom",
2 -> "Alsvin",
3 -> "Eddie"
)
//map_1 elements and length
println("The map_1 elements: " + map_1);
println("The map_1 size: " + map_1.size);
//empty map
val map_2 = scala.collection.mutable.Map()
//map_2 elements and length
println("The map_2 elements: " + map_2);
println("The map_2 size: " + map_2.size);
}