There are 2 variations for the syntax of Map.count() extension function. They are:
fun <K, V> Map<out K, V>.count(): Int
This extension function returns the number of entries in this map.
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.
In this example,
map1
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.count()
function on map1
without any predicate.3
because there are 3 entries in map1
.fun main(args: Array<String>) {
val map1 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
println(map1.count())
}
3
In this example,
map2
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.count()
function on map2
with a predicate that checks if the value is even.1
because there is 1 even value in map2
.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
println(map2.count { it.value % 2 == 0 })
}
1
In this example,
map3
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.count()
function on map3
with a predicate that checks if the key is 'b'.1
because there is 1 entry with key 'b' in map3
.fun main(args: Array<String>) {
val map3 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
println(map3.count { it.key == 'b' })
}
1
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.