The Analogy: A Copying Bureau's Two Ways of Working
A copying bureau takes in stacks of documents and sends them out copied, stapled and stamped. The old bureau ran three benches in a row, and each bench finished the whole stack before the next began. The first clerk photocopied every page in the stack and set the copies down in a pile; the second clerk stapled every copy in that pile and set them down again; the third clerk stamped every stapled copy. Between the benches stood tall intermediate piles, and every single page passed through every bench whether or not the customer would ever want it. If a hundred pages came in, a hundred were copied, a hundred stapled, a hundred stamped, before anyone looked at the result.
The new bureau hired one clerk who works a page at a time. She picks up a single page, copies it, staples that copy, stamps it, and drops the finished sheet in the out-tray -- and only then does she reach for the next page. Nothing piles up between stations, because there are no stations, only one page travelling through the whole process before its successor starts. The work is pulled through the pipeline sheet by sheet, on demand, rather than pushed through in great batches.
The pull-based way shows its worth when the docket does not ask for everything. Suppose the customer wants only the first three finished sheets. The single clerk copies, staples and stamps three sheets, sees the docket satisfied, and stops -- pages four onward are never touched. The old bureau, by contrast, would have copied all hundred pages before anyone counted to three, wasting ninety-seven pages of work. The bureau even keeps a roll of blank forms so long it may as well be endless; the clerk can pull as many as asked for, provided the docket says when to stop.
The catch is that the single clerk does nothing at all until an order is placed. You can hand her a card that says copy, then staple, then stamp, and walk away, and the out-tray stays empty, because the card is a set of instructions, not work performed; the work happens only when someone asks for finished sheets. And if you point her at the endless roll of forms and give her no stopping rule, she copies forever and never hands you a thing. The instructions are cheap and instant; the pulling is where the effort lives, and without a pull there is no effort and no result.
Syntax or Core Structure
A Kotlin Sequence is the single clerk: a lazy pipeline that does nothing until a terminal operation pulls values through it. You enter the lazy world with asSequence() on a collection, sequenceOf(...), or generateSequence(...) for an endless source, and you leave it with a terminal operation such as toList, sum, first or count.
fun main() {
val doubled = listOf(1, 2, 3, 4)
.asSequence()
.map { it * 2 }
.filter { it > 4 }
.toList()
println(doubled)
println(sequenceOf(10, 20, 30).sum())
println(generateSequence(1) { it * 2 }.take(5).toList())
}
Output:
[6, 8]
60
[1, 2, 4, 8, 16]
The first pipeline doubles each number to 2, 4, 6, 8 and keeps those above 4, giving [6, 8] once toList pulls the values through. The second sums a fixed sequence to 60. The third is the striking one: generateSequence(1) { it * 2 } describes an endless run of powers of two, but take(5) bounds it and toList pulls exactly five -- 1, 2, 4, 8, 16 -- and then stops. An infinite source is harmless as long as a terminal asks for a finite amount.
Technical Depth: How the Work Is Ordered
Bench by bench versus page by page
The clearest way to see the difference is to record the order in which each step touches each element. An eager collection runs each operation over the whole collection before the next operation starts; a sequence runs the whole pipeline on one element before moving to the next.
fun main() {
val log = mutableListOf<String>()
listOf(1, 2, 3)
.map { log.add("m" + it); it * 10 }
.filter { log.add("f" + it); it > 15 }
println("eager: " + log)
log.clear()
listOf(1, 2, 3).asSequence()
.map { log.add("m" + it); it * 10 }
.filter { log.add("f" + it); it > 15 }
.toList()
println("lazy: " + log)
}
Output:
eager: [m1, m2, m3, f10, f20, f30]
lazy: [m1, f10, m2, f20, m3, f30]
The eager log shows all three maps happening first -- m1, m2, m3 -- and only then all three filters over the mapped values, f10, f20, f30. That is bench by bench: the whole stack is copied before any of it is stamped, and an intermediate list of [10, 20, 30] existed between the two steps. The lazy log interleaves -- m1, f10, m2, f20, m3, f30 -- because each element travels through map and then filter before the next element is pulled. No intermediate list is ever built. Note the eager chain ran even though its result was discarded, because collection operations execute immediately whether or not you keep the answer.
The two worlds compared
| Aspect | Iterable (List) | Sequence |
|---|---|---|
| each step creates | a new intermediate collection | no intermediate collection |
| processing order | one step over the whole collection at a time | one element through the whole pipeline at a time |
short-circuit with take/first | no, computes everything then trims | yes, stops as soon as satisfied |
| infinite sources | not possible | possible with generateSequence |
| runs when | immediately, at each call | only when a terminal operation pulls |
| best for | small collections, few steps | large or infinite data, many steps, early exit |
Operations split into two kinds. Intermediate operations -- map, filter, take, drop, distinct, chunked, windowed, zip -- are lazy and return another Sequence, adding a station to the card without doing work. Terminal operations -- toList, sum, count, first, forEach, fold, sumOf, maxByOrNull -- are what pull values through and produce a result. A pipeline made only of intermediate operations has done nothing at all.
The distinction is not academic. On an eager list, a chain of five map and filter calls over a thousand elements allocates five intermediate lists totalling thousands of temporary objects, each fully built before the next begins. The same chain on a sequence allocates none of them: each element is drawn once and carried through all five stations, so the peak memory is a single element in flight rather than a thousand-element list per step. For a long pipeline over large data that difference is the whole reason sequences exist, and it is why converting with asSequence() can turn a memory-heavy chain into a streaming one without changing a single result.
Short-circuiting an endless source
A terminal that needs only some values stops the pull as soon as it is satisfied, which is what makes an infinite sequence usable. Recording how many elements are touched proves it.
fun main() {
val touched = mutableListOf<Int>()
val result = generateSequence(1) { it + 1 }
.map { touched.add(it); it * it }
.first { it > 20 }
println(result)
println(touched)
}
Output:
25
[1, 2, 3, 4, 5]
The source is endless -- 1, 2, 3, and on forever -- but first { it > 20 } pulls values only until one satisfies the predicate. The squares are 1, 4, 9, 16, 25; the fifth, 25, is the first above 20, so first returns it and stops. The touched log confirms only five elements were ever pulled from the infinite source. Had this been an eager list, there would be no list to begin with, because the source never ends.
Building a sequence by hand with yield
The sequence { ... } builder lets you produce values one at a time with yield, which is how you write a custom lazy source such as an endless Fibonacci run.
fun main() {
val fibs = sequence {
var a = 0
var b = 1
while (true) {
yield(a)
val next = a + b
a = b
b = next
}
}
println(fibs.take(5).toList())
println(fibs.takeWhile { it < 10 }.toList())
}
Output:
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5, 8]
Each yield(a) hands out the next Fibonacci number and suspends the block until the terminal pulls again, so the while (true) loop never runs away. take(5) pulls the first five -- 0, 1, 1, 2, 3 -- while takeWhile { it < 10 } keeps pulling until a value reaches 10, stopping after 8. The two terminals ask the same source for different amounts, and because this builder produces a fresh iterator each time, both calls work independently off the one fibs.
Real World Example: Scanning an Access Log for Admin Hits
A monitor scans access-log lines for hits on the admin path. A sequence is a natural fit -- the log could be huge, and we may want to stop early -- but the example also shows the sharpest edge of laziness.
fun main() {
val lines = listOf(
"200 /home",
"404 /admin",
"200 /login",
"500 /admin",
"403 /admin"
)
var parses = 0
val flagged = lines.asSequence()
.onEach { parses++ }
.filter { it.endsWith("/admin") }
val count = flagged.count()
val list = flagged.toList()
println("flagged count: " + count)
println("flagged lines: " + list)
println("parses: " + parses)
}
Output:
flagged count: 3
flagged lines: [404 /admin, 500 /admin, 403 /admin]
parses: 10
The pipeline reads plausibly: wrap the lines in a sequence, count each line as it passes through onEach, and keep only those ending in /admin. Three lines end in /admin -- the 404, the 500 and the 403 -- so count is 3 and list holds those three in order. The logic is correct, and for a genuinely large log the lazy pipeline would avoid building intermediate lists at each step.
The parses figure, however, is 10, not 5. There are only five lines, so how were there ten parses? Because flagged is a Sequence, a recipe rather than a result, and it was pulled twice: once by count, which walked all five lines, and again by toList, which walked all five again. Every terminal operation re-runs the entire pipeline from the source, so onEach fired five times per terminal, ten in all.
This is the design flaw, and it is the copying clerk asked to redo the whole job for each request. The fix is to pull once and reuse: call toList a single time, then take both the size and the contents from that list. The deeper lesson names itself -- a sequence is a set of instructions, not a stored answer, so each terminal pays the full cost again. A secondary smell compounds it: putting a side effect like parses++ inside a lazy intermediate operation means the number of times it runs depends on how many terminals consume the sequence and whether any of them short-circuit, which is exactly the kind of thing that should never hide inside a pipeline.
Common Mistakes
- Forgetting the terminal operation. A sequence pipeline of only
map,filterand friends does no work; it is a card of instructions. Nothing runs until a terminal such astoList,sumorfirstpulls values through.
- Running multiple terminals on one sequence. Each terminal re-evaluates the whole pipeline from the source, as the
parses: 10above showed. If you need the result more than once, materialise it withtoListand reuse the list.
- Reusing a constrain-once sequence. A sequence built from an
Iteratoror fromsequence { ... }can be consumed only once; a second terminal throwsIllegalStateException. Build a fresh sequence or convert to a list.
- Using a sequence for a tiny collection. The per-element machinery costs more than it saves on a handful of items. Plain list operations are simpler and faster until the data is large or the pipeline long.
- Leaving an infinite sequence unbounded.
generateSequencewith notake,takeWhileorfirstwill run forever when a terminal pulls it. Always give an endless source a stopping rule.
- Hiding side effects in intermediate operations. A mutation inside
maporonEachruns a number of times that depends on the terminals and any short-circuit, so its effect is unpredictable. Keep intermediates pure.
- Believing lazy and eager give different answers. They produce the same result; they differ only in when work happens and how much. Swapping one for the other for correctness reasons is a misunderstanding.
- Calling
toListin the middle of a pipeline. Materialising partway forces eager evaluation and discards laziness and short-circuiting for every step that follows. Stay in the sequence until the final terminal.
- Assuming
asSequencesnapshots the source. It wraps the collection; if the underlying list changes before a terminal runs, the sequence sees the change, and mutating during iteration can throwConcurrentModificationException.
Best Practices
- Use a sequence when the data is large or infinite, the pipeline has several steps, or you can exit early; use plain collection operations for small, short cases.
- Finish every pipeline with exactly one terminal operation, and materialise with
toListortoSetwhen the result will be read more than once.
- Bound every infinite
generateSequencewithtake,takeWhileorfirstso a terminal is guaranteed to return.
- Keep intermediate operations pure, and move any side effect to a single
forEachterminal where the number of executions is unambiguous.
- Prefer
first,findoranyoverfilter { ... }.first()when you need only one match, letting short-circuiting stop the pull early.
- Treat lazy and eager as equal in result and different in cost; choose between them for performance, not for the answer.
- Never reuse a constrain-once sequence; if two passes are needed, materialise the first pass into a list and iterate that.
- Measure before converting a hot path to a sequence, since the win comes from many elements or early exit, and small inputs pay overhead for nothing.
Practice Exercises
- Build the same
mapthenfilterpipeline twice -- once as an eager list chain, once as a lazy sequence -- each appending a label to a shared log inside the lambdas. Print both logs and explain why the orders differ.
- Use
generateSequenceto produce the powers of two, take the first eight, and print them. Then describe, without running it, what removing thetakewould do when the terminal runs.
- Reproduce the double-evaluation trap: build a sequence with an
onEachcounter, callcountand thentoListon it, and print the counter. Then restructure the code so the pipeline is pulled only once.
- Rewrite the access-log scanner to pull the filtered sequence a single time into a list, and derive both the flagged count and the flagged lines from that one list. Confirm the parse counter now reads five.