Kotlin List dropLastWhile()
Syntax & Examples
Syntax of List.dropLastWhile()
The syntax of List.dropLastWhile() extension function is:
fun <T> List<T>.dropLastWhile( predicate: (T) -> Boolean ): List<T>
This dropLastWhile() extension function of List returns a list containing all elements except last elements that satisfy the given predicate.
✐ Examples
1 Example
In this example,
- We create a list of integers
list
. - We use the
dropLastWhile
function with a predicate to drop elements greater than 3. - The resulting list
result
contains elements1, 2, 3
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 6)
val result = list.dropLastWhile { it > 3 }
print(result)
}
Output
[1, 2, 3]
2 Example
In this example,
- We create a list of characters
list
. - We use the
dropLastWhile
function with a predicate to drop elements until we encounter'c'
. - The resulting list
result
contains elementsa, b
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "b", "c", "d")
val result = list.dropLastWhile { it != "c" }
print(result)
}
Output
[a, b, c]
3 Example
In this example,
- We create a list of strings
list
. - We use the
dropLastWhile
function with a predicate to drop elements with length greater than 5. - The resulting list
result
contains elementsapple, banana
. - Finally, we print the
result
list to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "mango", "avocado")
val result = list.dropLastWhile { it.length > 5 }
print(result)
}
Output
[apple, banana, mango]
Summary
In this Kotlin tutorial, we learned about dropLastWhile() extension function of List: the syntax and few working examples with output and detailed explanation for each example.