Kotlin List – Check if all Elements Satisfy a Given Condition

To check if all elements of a List satisfy a given condition/predicate in Kotlin, call all() function on this List object and pass the predicate as argument to this function.

The Kotlin List.all() function checks if all the elements of the list match a given predicate, and returns a boolean value.

Syntax of List.all()

The syntax of List.all() function is

list.all(predicate)

where

ParameterDescription
predicateRequired. Predicate takes an element, and return a boolean value of true or false.

Return Value

List.all() function returns true if all elements match the given predicate, else the function returns false.

ADVERTISEMENT

Example 1: Check if All Elements Match given Predicate

In this example, we will take a list of strings, and check if all the strings match the predicate that the length of the string should be 2.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val predicate: (String) -> Boolean = { it.length == 2 }
    val result = list1.all(predicate)
    print("Does all elements match the given predicate? $result")
}

Output

Does all elements match the given predicate? false

Example 2: All Elements does not Match Predicate

In this example, we will take strings of different lengths, and check if list.all() function returns false for the predicate that the length of string should be 2.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("abc", "bcde", "cd", "de", "ef", "fg", "gh")
    val predicate: (String) -> Boolean = { it.length == 2 }
    val result = list1.all(predicate)
    print("Does all elements match the given predicate? $result")
}

Output

Does all elements match the given predicate? false

Conclusion

In this Kotlin Tutorial, we learned how to check if all the elements of a list match a given predicate, using Kotlin List.all() function.