Kotlin List findLast()
Syntax & Examples


Syntax of List.findLast()

The syntax of List.findLast() extension function is:

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

This findLast() extension function of List returns the last element matching the given predicate, or null if no such element was found.



✐ Examples

1 Example

In this example,

  • We create a list named list containing integers.
  • We use the findLast extension function on list to find the last element that satisfies the condition of being even.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5);
    val result = list.findLast { it % 2 == 0 };
    println(result);
}

Output

4

2 Example

In this example,

  • We create a list named list containing characters.
  • We use the findLast extension function on list to find the last element that is either 'p' or 'l'.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c', 'd', 'e');
    val result = list.findLast { it in listOf('p', 'l') };
    println(result);
}

Output

null

3 Example

In this example,

  • We create a list named list containing strings.
  • We use the findLast extension function on list to find the last element whose length is greater than 5.
  • The result is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "orange", "kiwi", "mango");
    val result = list.findLast { it.length > 5 };
    println(result);
}

Output

orange

Summary

In this Kotlin tutorial, we learned about findLast() extension function of List: the syntax and few working examples with output and detailed explanation for each example.