Kotlin List.all()
The Kotlin List.all() function returns true if all elements match the given predicate. Else, the function returns false.
Syntax
List.all(predicate)
Example 1
In this example,
- Take a list of numbers.
- Define a predicate that the number should be even.
- Call List.all() with predicate passed as argument.
- If all the elements of list matches the predicate, we should get true as return value from all().
Program
fun main(args: Array<String>) {
val list1 = listOf(4, 22, 8, 20)
val predicate: (Int) -> Boolean = {it % 2 == 0}
val result = list1.all(predicate)
print(result)
}
Output
true
Example 2
In this example,
- Take a list of numbers.
- Define a predicate that the number should be even.
- Call List.all() with predicate passed as argument.
- If any of the elements of list does not match the predicate, we should get false as return value from all().
Program
fun main(args: Array<String>) {
val list1 = listOf(4, 3, 8, 20)
val predicate: (Int) -> Boolean = {it % 2 == 0}
val result = list1.all(predicate)
print(result)
}
Output
false