The syntax of Map.all() extension function is:
fun <K, V> Map<out K, V>.all( predicate: (Entry<K, V>) -> Boolean ): Boolean
This all() extension function of Map returns true if all entries match the given predicate.
In this example,
map1
containing pairs of numbers and characters.all()
function on map1
with a predicate checking if each key is greater than zero.true
is returned; otherwise, false
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val allKeysGreaterThanZero = map1.all { entry -> entry.key > 0 }
println(allKeysGreaterThanZero)
}
true
In this example,
map2
containing pairs of characters and numbers.all()
function on map2
with a predicate checking if each value is greater than zero.true
is returned; otherwise, false
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val allValuesGreaterThanZero = map2.all { entry -> entry.value > 0 }
println(allValuesGreaterThanZero)
}
true
In this example,
map3
containing pairs of strings and numbers.all()
function on map3
with a predicate checking if each value is even.true
is returned; otherwise, false
is returned.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 10, "cherry" to 8)
val allValuesEven = map3.all { entry -> entry.value % 2 == 0 }
println(allValuesEven)
}
false
In this Kotlin tutorial, we learned about all() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.