Kotlin Set takeWhile()
Syntax & Examples
Set.takeWhile() extension function
The takeWhile() extension function in Kotlin returns a list containing the first elements that satisfy the given predicate.
Syntax of Set.takeWhile()
The syntax of Set.takeWhile() extension function is:
fun <T> Set<T>.takeWhile(predicate: (T) -> Boolean): List<T>
This takeWhile() extension function of Set returns a list containing first elements satisfying the given predicate.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
predicate | required | A function that takes an element and returns a Boolean indicating whether the element satisfies the predicate. |
Return Type
Set.takeWhile() returns value of type List
.
✐ Examples
1 Taking elements from a set of integers while they are less than 4
Using takeWhile() to get elements from a set of integers while they are less than 4.
For example,
- Create a set of integers.
- Use takeWhile() with a predicate that checks if the element is less than 4.
- Print the resulting list.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val result = numbers.takeWhile { it < 4 }
println(result)
}
Output
[1, 2, 3]
2 Taking elements from a set of strings while their length is less than 4
Using takeWhile() to get elements from a set of strings while their length is less than 4.
For example,
- Create a set of strings.
- Use takeWhile() with a predicate that checks if the length of the string is less than 4.
- Print the resulting list.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three", "four")
val result = strings.takeWhile { it.length < 4 }
println(result)
}
Output
[one, two]
3 Taking elements from a set of custom objects while they are younger than 30
Using takeWhile() to get elements from a set of custom objects while they are younger than 30.
For example,
- Create a data class.
- Create a set of custom objects.
- Use takeWhile() with a predicate that checks if the age of the person is less than 30.
- Print the resulting list.
Kotlin Program
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val result = people.takeWhile { it.age < 30 }
println(result)
}
Output
[Person(name=Bob, age=25)]
Summary
In this Kotlin tutorial, we learned about takeWhile() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.