Kotlin List.any() – Examples

Kotlin List.any()

The Kotlin List.any() function can be used to check if the list has at least one element, or if the list has at least one element that matches the given predicate.

Syntax 1

fun <T> Iterable<T>.any(): Boolean

Returns true if collection has at least one element.

Syntax 2

fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean

Returns true if at least one element matches the given predicate.

Example 1

In this example,

  1. Take a list of numbers.
  2. Call List.any() on the list. any() should return true.

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 3, 8, 20)
    val result = list1.any()
    print(result)
}

Output

true

Example 2

In this example,

  1. Take an empty list.
  2. Call List.any() on the list. any() should return false.

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 3, 8, 20)
    val result = list1.any()
    print(result)
}

Output

false

Example 3

In this example,

  1. Take a list of numbers.
  2. Define a predicate that the number should be even.
  3. Call List.any() with predicate passed as argument.
  4. If any the elements of list matches the predicate, we should get true as return value from any().

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 3, 18, 21)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.any(predicate)
    print(result)
}

Output

true

Example 4

In this example,

  1. Take a list of odd numbers.
  2. Define a predicate that the number should be even.
  3. Call List.any() with predicate passed as argument.
  4. If any the elements of list does not match the predicate, we should get false as return value from any().

Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 3, 15, 21)
    val predicate: (Int) -> Boolean = {it % 2 == 0}
    val result = list1.any(predicate)
    print(result)
}

Output

false