Kotlin List takeWhile()
Syntax & Examples
Syntax of List.takeWhile()
The syntax of List.takeWhile() extension function is:
fun <T> Iterable<T>.takeWhile( predicate: (T) -> Boolean ): List<T>
This takeWhile() extension function of List returns a list containing first elements satisfying the given predicate.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1
with elements1, 2, 3, 4, 5
. - We use the
takeWhile
function with a predicate{ it < 3 }
onlist1
to take elements until the predicate condition is no longer satisfied. - The result is a new list containing elements until the first element < 3, which is
[1, 2]
. - We print the result using
println()
.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.takeWhile { it < 3 }
println(result)
}
Output
[1, 2]
2 Example
In this example,
- We create a list of characters named
list1
with elements'a', 'b', 'c', 'd', 'e'
. - We use the
takeWhile
function with a predicate{ it < 'd' }
onlist1
to take elements until the predicate condition is no longer satisfied. - The result is a new list containing elements until the first element < 'd', which is
[a, b, c]
. - We print the result using
println()
.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf('a', 'b', 'c', 'd', 'e')
val result = list1.takeWhile { it < 'd' }
println(result)
}
Output
[a, b, c]
3 Example
In this example,
- We create a list of strings named
list1
with elements"apple", "banana", "cherry", "date", "elderberry"
. - We use the
takeWhile
function with a predicate{ it.length <= 6 }
onlist1
to take elements until the predicate condition is no longer satisfied. - The result is a new list containing elements until the length of an element is not less than or equal to 6 characters, which is
["apple", "banana", "cherry"]
. - We print the result using
println()
.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry", "date", "elderberry")
val result = list1.takeWhile { it.length <= 6 }
println(result)
}
Output
[apple, banana, cherry, date]
Summary
In this Kotlin tutorial, we learned about takeWhile() extension function of List: the syntax and few working examples with output and detailed explanation for each example.