Kotlin List.any() Function

The Kotlin List.any() function checks if there is at least one element in the list.

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 is

list.any()

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

list.any(predicate)

If a predicate is given to any() function, then it returns true if at least one element matches the given predicate.

Example 1: 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

Example 2: 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

Conclusion

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