Kotlin List dropWhile()
Syntax & Examples


Syntax of List.dropWhile()

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

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

This dropWhile() extension function of List returns a list containing all elements except first elements that satisfy the given predicate.



✐ Examples

1 Example

In this example,

  • We create a list of integers list.
  • We use the dropWhile function with a predicate to drop elements until we encounter an element greater than or equal to 4.
  • The resulting list result contains elements 4, 5, 6.
  • 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.dropWhile { it < 4 }
    print(result)
}

Output

[4, 5, 6]

2 Example

In this example,

  • We create a list of characters list.
  • We use the dropWhile function with a predicate to drop elements until we encounter 'c'.
  • The resulting list result contains elements c, d.
  • 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.dropWhile { it != &quot;c&quot; }
    print(result)
}

Output

[c, d]

3 Example

In this example,

  • We create a list of strings list.
  • We use the dropWhile function with a predicate to drop elements until we encounter an element with a length greater than or equal to 6.
  • The resulting list result contains elements mango, avocado.
  • 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.dropWhile { it.length < 6 }
    print(result)
}

Output

[banana, mango, avocado]

Summary

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