Kotlin Tutorials

Kotlin Map all()
Syntax & Examples

Syntax of Map.all()

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.



✐ Examples

1 Check if all keys are greater than zero

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We then apply the all() function on map1 with a predicate checking if each key is greater than zero.
  • If all keys are greater than zero, true is returned; otherwise, false is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

true

2 Check if all values are greater than zero

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We then apply the all() function on map2 with a predicate checking if each value is greater than zero.
  • If all values are greater than zero, true is returned; otherwise, false is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

true

3 Check if all values are even

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We then apply the all() function on map3 with a predicate checking if each value is even.
  • If all values are even, true is returned; otherwise, false is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

false

Summary

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.