Kotlin Map - Size Property



The Kotlin Map size property is an attribute of the collection interface, used to return the number of elements available in the map.

We can access the size property directly without calling the function.

Syntax

Following is the syntax of Kotlin map size property −

Map.size

Parameters

size is a property so it does not accepts any parameters.

Return value

The size property returns the integer value that represents the length of the map.

Example 1: If Map is not Empty

Let's see a basic example of the size property, which returns number of elements in the map.

fun main(args: Array<String>) {
   val map = mapOf(1 to "aman", 2 to "tutorialspoint", 3 to "India")
   val totalElement = map.size
   println("Total number of elements: $totalElement")
}

Output

Following is the output −

Total number of elements: 3

Example 2: Map with Different Types of Element

The following example gives the total number of elements in the current map −

fun main(args: Array<String>) {
   val map = mapOf<Any, Any>(1 to 'A', 2 to "tutorialspoint", 3 to "India", 4 to "10", 5 to 5)
   val totalElement = map.size
   println("Total number of elements: $totalElement")
}

Output

Following is the output −

Total number of elements: 5

Example 3: If Map is Empty

This is another example of size property. If the map is empty, it returns 0 −

fun main(args: Array<String>) {
   val map = mapOf<Any, Any>()
   val totalElement = map.size
   println("Total number of elements: $totalElement")
}

Output

Following is the output −

Total number of elements: 0
kotlin_maps.htm
Advertisements