Skip to workspace
Kotlin Lab

Working with data / Chapter 07

Stop searching once seats fill

Use a lazy pipeline when the number of predicate calls is observable.

The decision

A dispatcher asks for up to n available drivers from a priority list. Each availability check contacts a local scheduling adapter. Probe in priority order and stop once the request is filled; n of zero or less means no probes.

Read the Kotlin

Count the probes as well as the results

On a List, filter builds its entire result before take gets it. A Sequence passes one input through the stages at a time when a terminal operation such as toList() asks for results. Once take has enough matches, it stops requesting inputs. Trace a few rejected entries too, since each rejection still calls the predicate.

listOf(1, 4, 5, 8, 9).asSequence()
    .filter { it % 2 == 0 }.take(2).toList()
// Tests 1, 4, 5, 8. The last 9 is never inspected.

Distinguish the first match from the best match

A source can yield a qualifying driver immediately even if a better one appears later. Inserting sorted() before take(1) forces the sort to consume the matches before producing its first value. If the requirement is just the smallest time, minOrNull() can track the minimum in one traversal and returns null for an empty source.

Define what a zero or negative limit does

A zero-length shortlist must skip the availability probe completely. Kotlin Sequence.take accepts zero and rejects negative counts with IllegalArgumentException. The lesson explicitly normalizes a negative request with coerceAtLeast(0). Removing that call changes behavior even if every positive example still passes.

val requested = -1
val limit = requested.coerceAtLeast(0)
drivers.asSequence().filter(available).take(limit).toList()  // no probes

The full example

Java 25
import java.util.List;
import java.util.function.Predicate;

class Lesson {
    static List<String> shortlist(List<String> drivers, int n,
                                  Predicate<String> available) {
        return drivers.stream().filter(available)
            .limit(Math.max(0, n)).toList();
    }
}
Kotlin/JVM
fun shortlist(
    drivers: List<String>,
    n: Int,
    available: (String) -> Boolean
): List<String> =
    drivers.asSequence()
        .filter(available)
        .take(n.coerceAtLeast(0))
        .toList()

Inputs and outcomes

InputOutcomeWhy it matters
Ada busy, Bo free, Cy free · n = 1[Bo]; probe Ada and BoOnce Bo fills the request, Cy is never queried.
Ada free · n = 0[]; no probesAn empty request takes no work.
Bo busy, Cy free · n = 3[Cy]; probe bothExhaustion returns fewer than three drivers.

Walk through the code

  1. Java’s sequential stream defers filter until a terminal operation consumes it. Kotlin’s List.filter evaluates the predicate for every element before a following take can limit the result.
  2. asSequence makes the filter lazy. toList asks for elements, take stops asking after n matches, and the predicate sees only the necessary prefix. A negative n is explicitly normalized to zero before take.
  3. For [Ada busy, Bo free, Cy free] and n = 1, both a list and a sequence can return [Bo]. Recording the predicate calls shows why they are different contracts.

The Java habit

Porting stream().filter(...).limit(n) to list.filter(...).take(n) preserves many result lists but can perform expensive or observable work after the last needed result.

When to choose differently

For a small list that must be processed in full with a trivial transformation, the sequence machinery can cost more than it saves. Measure that path, or use a clear loop.

References

Open quizTry code