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(): IntThis extension function returns the number of entries in this map.
2.
fun <K, V> Map<out K, V>.count( predicate: (Entry<K, V>) -> Boolean ): IntThis 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
map1with key-value pairs('a' to 1), ('b' to 2), ('c' to 3). - We use the
count()function onmap1without any predicate. - The output is
3because there are 3 entries inmap1.
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
map2with key-value pairs('a' to 1), ('b' to 2), ('c' to 3). - We use the
count()function onmap2with a predicate that checks if the value is even. - The output is
1because there is 1 even value inmap2.
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
map3with key-value pairs('a' to 1), ('b' to 2), ('c' to 3). - We use the
count()function onmap3with a predicate that checks if the key is 'b'. - The output is
1because there is 1 entry with key 'b' inmap3.
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.