Kotlin List takeLastWhile()
Syntax & Examples


Syntax of List.takeLastWhile()

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

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

This takeLastWhile() extension function of List returns a list containing last elements satisfying the given predicate.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 10, 20, 30, 40, 50.
  • We apply takeLastWhile on list1 with the predicate { it > 25 }, which means to take elements from the list while they are greater than 25.
  • The result, which is a new list containing the elements 30, 40, 50, is stored in result.
  • Finally, we print the value of result to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30, 40, 50);
    val result = list1.takeLastWhile { it > 25 };
    print(result);
}

Output

[30, 40, 50]

2 Example

In this example,

  • We create a list named list1 containing the strings "apple", "banana", "grape", "orange".
  • We apply takeLastWhile on list1 with the predicate { it.length == 6 }, which means to take elements from the list from the trailing end while their length is 6.
  • The result, which is a new list containing the element "orange", is stored in result, because the while condition is broken for the element "grape".
  • Finally, we print the value of result to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "grape", "orange");
    val result = list1.takeLastWhile { it.length == 6 };
    print(result);
}

Output

[orange]

Summary

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