Kotlin Map any()
Syntax & Examples
Syntax of Map.any()
There are 2 variations for the syntax of Map.any() extension function. They are:
1.
fun <K, V> Map<out K, V>.any(): BooleanThis extension function returns true if map has at least one entry.
2.
fun <K, V> Map<out K, V>.any( predicate: (Entry<K, V>) -> Boolean ): BooleanThis extension function returns true if at least one entry matches the given predicate.
✐ Examples
1 Check if any entry exists in the map
In this example,
- We create a map named
map1with three key-value pairs. - We then use the
any()function to check ifmap1has at least one entry, which it does. - The result, which is
true, is printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map1.any()
println(result)
}Output
true
2 Check if any entry matches a predicate in the map
In this example,
- We create a map named
map2with three key-value pairs. - We then use the
any()function with a predicate that checks if any entry's value is equal to 2 inmap2. - As one entry ('b' -> 2) matches the predicate, the result is
true, which is printed to standard output.
Kotlin Program
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)
}Output
true
3 Check if any entry with a specific key exists in the map
In this example,
- We create a map named
map3with three key-value pairs. - We then use the
any()function with a predicate that checks if any entry's key is equal to 'd' inmap3. - As no entry has a key 'd', the result is
false, which is printed to standard output.
Kotlin Program
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)
}Output
false
Summary
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.