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 elements 1, 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 elements a, b.
  • Finally, we print the result list to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;)
    val result = list.dropLastWhile { it != &quot;c&quot; }
    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 elements apple, banana.
  • Finally, we print the result list to standard output using print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;mango&quot;, &quot;avocado&quot;)
    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.