Kotlin Tutorials

Kotlin Map count()
Syntax & Examples

Syntax of Map.count()

There are 2 variations for the syntax of Map.count() extension function. They are:

1.
fun <K, V> Map<out K, V>.count(): Int

This extension function returns the number of entries in this map.

2.
fun <K, V> Map<out K, V>.count( predicate: (Entry<K, V>) -> Boolean ): Int

This extension function returns the number of entries matching the given predicate.



✐ Examples

1 Count the number of entries in the map

In this example,

  • We create a map named map1 with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3).
  • We use the count() function on map1 without any predicate.
  • The output is 3 because there are 3 entries in map1.

Kotlin Program

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

Output

3

2 Count the number of even values in the map

In this example,

  • We create a map named map2 with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3).
  • We use the count() function on map2 with a predicate that checks if the value is even.
  • The output is 1 because there is 1 even value in map2.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
    println(map2.count { it.value % 2 == 0 })
}

Output

1

3 Count the number of entries with key 'b' in the map

In this example,

  • We create a map named map3 with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3).
  • We use the count() function on map3 with a predicate that checks if the key is 'b'.
  • The output is 1 because there is 1 entry with key 'b' in map3.

Kotlin Program

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

Output

1

Summary

In this Kotlin tutorial, we learned about count() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.