Kotlin Sequence.filter and take
A sequence evaluates intermediate operations lazily. Combining filter with take lets a terminal operation stop as soon as enough matches are available.
A simple example
Sequence.filter and take
- Start with Numbers 1, 2, 3, 4
- Do this Filter evens and take the first
- Result 2
Syntax
source.asSequence().filter(predicate).take(limit).toList()
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Stop reading once two matches are found
A search needs just the first two matching entries from a longer input. Stop processing when the requirement has been met while keeping the original order of the selected matches.
fun main() {
var inspected = 0
val result = (1..100).asSequence().onEach { inspected++ }
.filter { it % 2 == 0 }.take(2).toList()
println(result)
println(inspected)
}
[2, 4] 4
The counter shows exactly which values were inspected. A value after the second even number is never visited in this pipeline.
Kotlin documentation for Sequence.filter and take
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The next tray takes only the first two positive quantities. Which quantities reach it?
Review print quantities
A print room records four job quantities, including a cancelled job. The next tray takes only the first two positive quantities. Which quantities reach it?