The dropWhile() extension function for sets in Kotlin returns a list containing all elements of the set except the first elements that satisfy the given predicate.
The syntax of Set.dropWhile() extension function is:
fun <T> Set<T>.dropWhile(predicate: (T) -> Boolean): List<T>
This dropWhile() extension function of Set returns a list containing all elements except the first elements that satisfy the given predicate.
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element of the set and returns a Boolean indicating whether the element satisfies the condition. |
Set.dropWhile() returns value of type List
.
In Kotlin, we can use the dropWhile()
function to get a list of elements from a set, excluding the first elements that are less than 3.
For example,
dropWhile()
function with a predicate that checks if an element is less than 3.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val droppedNumbers = numbers.dropWhile { it < 3 }
println("Elements after dropping those less than 3: $droppedNumbers")
}
Elements after dropping those less than 3: [3, 4, 5]
In Kotlin, we can use the dropWhile()
function to get a list of elements from a set of strings, excluding the first elements that start with a vowel.
For example,
dropWhile()
function with a predicate that checks if the first character of the string is a vowel.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "apricot", "cherry")
val droppedFruits = fruits.dropWhile { it.first() in "aeiou" }
println("Elements after dropping those starting with a vowel: $droppedFruits")
}
Elements after dropping those starting with a vowel: [banana, apricot, cherry]
In Kotlin, we can use the dropWhile()
function on an empty set, which will return an empty list regardless of the predicate.
For example,
dropWhile()
function with a predicate that checks if an element is positive.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val droppedElements = emptySet.dropWhile { it > 0 }
println("Elements after applying dropWhile on empty set: $droppedElements")
}
Elements after applying dropWhile on empty set: []
In this Kotlin tutorial, we learned about dropWhile() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.