Kotlin Tutorials

Kotlin Map size
Syntax & Examples

Syntax of Map.size

The syntax of Map.size property is:

abstract val size: Int

This size property of Map returns the number of key/value pairs in the map.



✐ Examples

1 Get size of a map with integer keys and character values

In this example,

  • We create a map named map with integer keys and character values.
  • We access the size property of the map to get the number of key/value pairs.
  • We then print the size to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val size = map.size
    println(size)
}

Output

3

2 Get size of a map with string keys and integer values

In this example,

  • We create a map named map with string keys and integer values.
  • We access the size property of the map to get the number of key/value pairs.
  • We then print the size to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
    val size = map.size
    println(size)
}

Output

3

3 Print size of a map using string interpolation

In this example,

  • We create a map named map with integer keys and character values.
  • We directly print the size of map using string interpolation.
  • The size of the map is interpolated into the output string.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    println("Size of the map: $map.size")
}

Output

Size of the map: 3

Summary

In this Kotlin tutorial, we learned about size property of Map: the syntax and few working examples with output and detailed explanation for each example.