Kotlin List – Check if any of the Elements Satisfy a Given Condition

To check if at least one of the elements of this List satisfy a given condition/predicate, call any() function on this List object and pass the predicate as argument to the function.

The Kotlin List.any() function checks if there is at least one element in the list, and returns a boolean value.

The Kotlin List.any(predicate) function checks if any one of element in the list matches the given predicate.

So, the working of any() depends on if an argument is given to it.

Syntax of List.any()

The syntax of List.any() function with a predicate passed to it is

list.any(predicate)

The function returns true if at least one element matches the given predicate.

If no argument is given to any() function, then it returns true if collection has at least one element.

list.any()
ADVERTISEMENT

Example 1: Check if At least one element of List matches Predicate

In this example, we will take a list of elements, of type string, and check if at least one of the elements matches the given predicate that the length of string is 3.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bcd", "cdef")
    val predicate: (String) -> Boolean = {it.length == 3}
    val anyElementMatchesPredicate = list1.any(predicate)
    println("Does at least one element in list matches predicate? $anyElementMatchesPredicate")
}

Output

Does at least one element in list matches predicate? true

Example 2: Check if List has At least One Element

In this example, we will take two lists: list1 with two elements, and list2 with no elements. We will call list.any() function on these lists, and observe the output in the two scenarios.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc")
    val list2 = listOf<String>()
    val anyInList1 = list1.any()
    val anyInList2 = list2.any()
    println("Does list1 have at least one element? $anyInList1")
    println("Does list2 have at least one element? $anyInList2")
}

Output

Does list1 have at least one element? true
Does list2 have at least one element? false

Conclusion

In this Kotlin Tutorial, we learned how to check if at least one of the elements in this list matches the given predicate, using Kotlin List.any() function.