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
list1containing the integers10, 20, 30, 40, 50. - We apply
takeLastWhileonlist1with the predicate{ it > 25 }, which means to take elements from the list while they are greater than25. - The result, which is a new list containing the elements
30, 40, 50, is stored inresult. - Finally, we print the value of
resultto 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
list1containing the strings"apple", "banana", "grape", "orange". - We apply
takeLastWhileonlist1with the predicate{ it.length == 6 }, which means to take elements from the list from the trailing end while their length is6. - The result, which is a new list containing the element
"orange", is stored inresult, because the while condition is broken for the element"grape". - Finally, we print the value of
resultto 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.