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 elements4, 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 elementsc, d
. - 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.dropWhile { it != "c" }
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 elementsmango, avocado
. - 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.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.