There are 2 variations for the syntax of Map.any() extension function. They are:
fun <K, V> Map<out K, V>.any(): Boolean
This extension function returns true if map has at least one entry.
fun <K, V> Map<out K, V>.any( predicate: (Entry<K, V>) -> Boolean ): Boolean
This extension function returns true if at least one entry matches the given predicate.
In this example,
map1
with three key-value pairs.any()
function to check if map1
has at least one entry, which it does.true
, is printed to standard output.fun main(args: Array<String>) {
val map1 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map1.any()
println(result)
}
true
In this example,
map2
with three key-value pairs.any()
function with a predicate that checks if any entry's value is equal to 2 in map2
.true
, which is printed to standard output.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map2.any { entry -> entry.value == 2 }
println(result)
}
true
In this example,
map3
with three key-value pairs.any()
function with a predicate that checks if any entry's key is equal to 'd' in map3
.false
, which is printed to standard output.fun main(args: Array<String>) {
val map3 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map3.any { entry -> entry.key == 'd' }
println(result)
}
false
In this Kotlin tutorial, we learned about any() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.