Library contents

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

  1. Start with Numbers 1, 2, 3, 4
  2. Do this Filter evens and take the first
  3. Result 2
The lazy sequence stops once one even result is available.

Syntax

Kotlin 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.

From the programvar inspected = 0
First output line[2, 4]
Lesson.kt
fun main() {
    var inspected = 0
    val result = (1..100).asSequence().onEach { inspected++ }
        .filter { it % 2 == 0 }.take(2).toList()
    println(result)
    println(inspected)
}
Output
[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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result6 · 2

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?

Given3 · 0 · 8 · 3
Worked result3 · 8