Part 10 / Topic 5 of 8
Sequences vs collections: eager vs lazy
A List chain is eager: map runs to completion over every element — a whole new List —
before filter even starts. Each step is a separate full pass over the data.
var listSteps = 0
val eager = SHIPMENTS
.map { listSteps++; it.weightKg }
.filter { listSteps++; it > 500.0 }
.take(2)
println("List result $eager after $listSteps steps")
.asSequence() switches to lazy, element-by-element evaluation: nothing runs until a
terminal operation (toList(), first(), sum(), ...) is called, and take(2) can stop
the whole pipeline early the moment it has enough.
var seqSteps = 0
val lazy = SHIPMENTS.asSequence()
.map { seqSteps++; it.weightKg }
.filter { seqSteps++; it > 500.0 }
.take(2)
.toList()
println("Sequence result $lazy after $seqSteps steps")
List result [1200.0, 2400.0] after 10 steps
Sequence result [1200.0, 2400.0] after 8 steps
Sequence order: [map S-2001, filter S-2001, map S-2002, filter S-2002]
Generated: [S-2006, S-2007, S-2008]
The step count alone doesn't prove laziness — the step order does. The sequence interleaves
one map then one filter per element, processing S-2001 completely before S-2002 is
even looked at, instead of mapping everything and only then filtering everything, which is what
the List version does. generateSequence(2006) { it + 1 } builds an infinite sequence; take
is what makes consuming it finite.
🔍 Going deeper: reach for a
Listfor small data you'll read more than once; reach for aSequencefor a long chain ofmap/filter-style steps, or whenever an early exit liketake()/first()/any()means most of the data never needs to be touched at all. For a five-element list the difference is academic; for a pipeline over a real dataset with an early exit, it's the difference between scanning everything and stopping after a handful of items.
Full program: examples/05_sequences_vs_collections.kt.
Done here? The practice set for Part 10 — including the solutions — is on the part page.