Kotlin List.findLast()

The Kotlin List.findLast() function is used to get the last element from the List that matches the given predicate.

Syntax

The syntax of List.findLast() function is

</>
Copy
fun <T> List<T>.findLast(predicate: (T) -> Boolean): T?

where T can be any builtin datatype or user-defined datatype.

Examples

In the following example, we have a list of strings. We get the last string whose length is 6.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf("apple", "banana", "cherry", "avocado")
    var result = list.findLast{ it.length == 6}
    println(result)
}

Output

cherry

In the following example, we take a list of numbers, and find the last element which is exactly divisible by 5.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf(2, 4, 10, 14, 20, 22)
    var result = list.findLast{ it % 5 == 0}
    println("Output : " + result)
}

Output

Output : 20

Conclusion

In this Kotlin Tutorial, we learned how to get the last element of this list that matches the given predicate, using Kotlin List.findLast() function.