1. Introduction
When we write code over collections, it’s very easy to fall into a pleasant trap: the chain looks nice, reads like text, and you want to believe it “runs nicely” too. Often that’s true. But sometimes a single line hides several full passes over the data and a pile of temporary lists that get created and immediately thrown away.
This is not “micro-optimization for a checkbox”, but a normal engineering habit: understanding how much work your code actually does, especially if the data set becomes 100 times larger.
Imagine that we don’t have 20 expenses but 200_000, and the user asks for a “top-10 categories” report. If our code makes four passes and builds three intermediate lists, it can still be correct — but it will simply waste extra time and memory.
We won’t measure milliseconds or draw profiler charts (that’s a separate story), but we will learn to read a pipeline “by cost”, like an estimate for a renovation: “there’s an extra coat of plaster here”.
2. Pipeline cost: passes, collections, and objects
When you see a chain like filter().map().filter().map(), it has a price. And that price usually consists of three parts: how many times we walked over the source data, how many intermediate collections we created between steps, and how many temporary objects we produced along the way (for example, new strings, Pair, Triple, etc.). This model is useful even without exact numbers: you start noticing “extra movement” in the code.
Let’s lock this in with a small table — no fanaticism, just to have a reference point:
| What happens | How it shows up in code | What it can lead to |
|---|---|---|
| Extra passes over the data | multiple steps, each “over everything again” | extra CPU time |
| Intermediate collections | a chain on List often materializes the result of each step | extra memory + garbage collection |
| Temporary objects | we often create new elements (for example, map { ... }) | GC pressure, especially with large volumes |
Important: sometimes readability matters more, and you deliberately keep “two clear steps” instead of one clever step. But that should be a conscious choice, not an accident.
How to mentally “estimate” a pipeline by execution
It helps to keep a simple picture in mind: let’s imagine the pipeline as an assembly line.
flowchart TD
A[List: исходные данные] --> B[filter]
B --> C[map]
C --> D[filter]
D --> E[toList / fold / count]
When this is a List, many steps (roughly B, C, D) often create intermediate lists: the result of filter is a list, the result of map is a list, and so on.
When this is a Sequence, steps B, C, D are usually not materialized until the terminal operation E happens. Then elements flow “one by one” through the whole conveyor. This idea of “intermediate vs. terminal” and “laziness” is key to understanding why Sequence can reduce the number of intermediate collections.
3. Extra passes and intermediate collections
Extra passes: where they appear “out of habit”
A very typical pattern among beginners (and, honestly, among adult developers when they’re tired) looks like this: “first I’ll filter”, and then “separately I’ll compute”. This is fine… while there isn’t much data. But it’s useful to understand that this is two passes: one for filter, another for fold/sum.
Suppose we have expenses as Triple(id, category, amount). No OOP for now — we’re in the part of the course where we build the project “with functions and collections”.
fun main() {
val expenses = listOf(
Triple(1, "food", 120),
Triple(2, "taxi", 250),
Triple(3, "food", 80),
)
val foodOnly = expenses.filter { it.second == "food" }
val totalFood = foodOnly.fold(0) { acc, e -> acc + e.third }
println(totalFood) // 200
}
The code reads perfectly: first we kept only food, then we summed the amounts. But the execution model is this: we walked over expenses, built a new list foodOnly, then walked over foodOnly one more time and computed the sum.
fold itself is a standard way to “accumulate a total”, and it sequentially combines the accumulator with the elements.
Can we do it in one pass? Yes. Do we always need to? No. But being able to is useful.
Intermediate collections: what happens in a chain on List
When you call operations like filter and map on a regular collection (List), you typically get a new list as the result of each step. That is, the chain:
val result = xs.filter { ... }.map { ... }.filter { ... }
in the conceptual model does roughly this:
- built a list after the first filter
- built a list after map
- built a list after the second filter
And only then do you see the final result.
This is not “bad” and not a “Kotlin mistake”. On the contrary: such a contract makes code predictable, because each step gives you a ready collection. But if there are many steps and lots of data, you start paying for every intermediate list.
4. Sequence: when it helps and when it hurts
Where Sequence really helps
Sequence is useful not because it is “magically faster always”, but because it changes the execution model: operations become lazy, and elements can flow through the chain “as a stream”, without intermediate lists — until you request a result with a terminal operation.
A particularly strong effect appears when we have “early termination”: for example, take(n) or searching for the first matching element. The point is: if we only need 5 elements, we don’t need to process 100_000.
To see the idea, let’s make an example not about expenses but about numbers (it’s easier to read visually). The technique is the same.
fun main() {
val xs = (1..1_000).toList()
val firstFive = xs.asSequence()
.map { it * it }
.filter { it % 10 == 0 }
.take(5)
.toList()
println(firstFive) // [100, 400, 900, 1600, 2500]
}
What matters here is that take(5) is the operation “take the first N”. In a lazy model this often means we won’t process the tail that won’t make it into the result anyway.
If we did the same thing on a List without Sequence, we would most likely first build a list of squares for all 1000 numbers, then filter, then take 5. On 1000 elements the difference is negligible, but on 10_000_000 it can already be very noticeable.
Where Sequence can get in the way
Sequence is a tool, not a religion. Sometimes it makes life harder, because laziness adds a “time factor”: it’s not always obvious when exactly the code inside map/filter will run.
There’s also a nuance that often surprises beginners: you can accidentally iterate a Sequence multiple times, and then the work will be done multiple times.
Let’s look at an example. We’ll build a chain and then request the result twice via different terminal operations.
fun main() {
val xs = listOf(1, 2, 3, 4)
val seq = xs.asSequence()
.map { x ->
println("map $x")
x * 10
}
println(seq.count()) // map 1..4 will be printed, count = 4
println(seq.toList()) // map 1..4 will be printed AGAIN
}
The output will be roughly like this (simplified):
map 1
map 2
map 3
map 4
4
map 1
map 2
map 3
map 4
[10, 20, 30, 40]
And that’s logical: Sequence is not a “ready result”, but a “description of how to obtain elements”. So if you request the result twice, the elements are computed twice.
With a regular List, you would build the new list once and then reuse it. So sometimes Sequence doesn’t speed things up — it actually adds work if you keep “pulling the result” multiple times.
A practical rule of thumb is: if you built a Sequence and want to use the outcome more than once, it often makes sense to materialize it into a List once via toList() and then work with that.
Side effects as a problem amplifier
There’s one more reason why Sequence sometimes “gets in the way”: side effects (for example, println) inside map/filter become tied to the moment of execution, and that moment is delayed until a terminal operation. You saw this idea in the previous lecture as “why nothing happened”.
Today we care about something else: side effects make the pipeline harder to understand and sometimes lead to repeated work (as in the example above), and repeated work = repeated side effects. If you send a log inside map, it will be sent as many times as you requested a terminal result. Sometimes that’s fine. Sometimes it’s “why do I have 2000 identical lines in the logs”.
In learning examples, we sometimes use println inside chains on purpose, as a highlight. But in real code it’s better to keep transformations “pure” and keep effects separate. This is especially important when you move to lazy computations.
5. Practice: an expense report without extra work
Now let’s carefully tie everything to our practical console project (let’s call it BudgetCli). Reminder of the data format: a list of Triple(id, category, amount). Our goal is to build a “top-N categories by total” report.
A readable report variant
First, let’s write the most straightforward variant: collect totals by category, turn that into a list, sort it, take take(n).
fun main() {
val expenses = listOf(
Triple(1, "food", 120),
Triple(2, "taxi", 250),
Triple(3, "food", 80),
Triple(4, "books", 300),
)
val totals = expenses.fold(mutableMapOf<String, Int>()) { acc, e ->
acc[e.second] = (acc[e.second] ?: 0) + e.third
acc
}
val top2 = totals.entries
.sortedByDescending { it.value }
.take(2)
println(top2) // [books=300, food=200]
}
Here fold does a clear thing: it accumulates a structure (MutableMap) one element at a time. It’s important that the accumulator in fold can be more than just a number — that’s a standard idea for aggregations.
But then there’s a point: sortedByDescending returns a new list (i.e., materializes the sorted result), and only then take(2) takes the first two. For a small number of categories, this is fine. But if there are very many categories, sorting the entire list just to get top-2 is rather expensive.
We won’t study “advanced data structures” and algorithms for selecting top-N without a full sort yet (that’s a different layer of topics). But we can at least understand: sorting everything is work.
Where Sequence helps in the project, and where it doesn’t
At this point many people automatically say: “Oh, let’s use asSequence()”. And this is where adult engineering begins: you need to ask yourself — what exactly will get better?
If we have:
- little data (tens/hundreds),
- a short chain (2–3 steps),
- the full result is needed,
then Sequence often gives no benefit, and sometimes makes the code slightly less obvious.
But if we have:
- a long chain,
- potential early termination,
- many intermediate steps (especially map/filter/map/filter/...),
then Sequence can reduce the number of intermediate collections.
For example, if we want to take only the first few “suspicious” operations (say, expenses greater than 500), then Sequence + take(n) is a good candidate.
fun main() {
val expenses = listOf(
Triple(1, "food", 120),
Triple(2, "taxi", 250),
Triple(3, "books", 900),
Triple(4, "taxi", 700),
Triple(5, "food", 50),
)
val bigOnes = expenses.asSequence()
.filter { it.third >= 500 }
.take(2)
.toList()
println(bigOnes) // [(3, books, 900), (4, taxi, 700)]
}
Here take(2) is very important: it gives us a chance not to process the tail of the list if the first two matching elements are found early. The idea of take is to “limit the number of elements”, and it fits the lazy model well.
“Merging steps” instead of extra collections
Sometimes the best way to speed up a pipeline is not laziness but fewer steps. For example, instead of:
filter → map → filterNotNull
you can use a single operation mapNotNull. You already covered this in the lectures about data cleanup and changing types.
In our project this is useful when parsing input lines. Suppose we have raw commands and we want to extract only amounts (as Int), skipping junk.
fun main() {
val rawAmounts = listOf("120", " ", "oops", "250")
val amounts = rawAmounts.mapNotNull { it.trim().toIntOrNull() }
println(amounts) // [120, 250]
}
Here we made one pass and immediately got a “clean” List<Int>. If we had done map { ... } returning Int? and then filterNotNull, that would be two steps. Again: sometimes two steps are more readable, and that’s fine. But now you at least understand the cost.
6. A practical rule of thumb: List or Sequence
It’s important not to turn the course into a Sequence cult, so let’s fix a sane intuition. If your chain is short and clear, and the data volume is small, then regular operations on List are an excellent choice: readable, predictable, easy to debug. The Kotlin standard library is designed with the expectation that you actively use map/filter/reduce/fold and aren’t afraid of it.
If the chain is long, the data is large, and especially if there is take(n) or “find the first match”, then Sequence becomes a useful candidate, because it can remove intermediate collections and stop earlier.
But if you plan to use the result multiple times, then Sequence can be harmful: you can accidentally compute the same thing multiple times. Then it’s better to materialize into a List once (via toList()) and then work with the ready data.
7. Typical mistakes when trying to “optimize a pipeline”
Mistake #1: optimizing without understanding what exactly you’re optimizing.
It’s very easy to replace list.filter { ... }.map { ... } with list.asSequence().filter { ... }.map { ... }.toList() and proudly assume it’s faster. But if there’s little data and the chain is short, you might gain nothing, while the code becomes slightly less transparent. It’s better to first learn to see extra steps and intermediate lists, and only then choose the tool.
Mistake #2: reusing a Sequence as if it were a ready result.
Sequence is a “recipe”, not a “finished dish”. If you run a terminal operation twice (for example, count(), then toList()), the recipe will be cooked twice. This is especially painful if the pipeline contains heavy computations or side effects (println, logging).
Mistake #3: side effects inside map/filter and surprise at “weird execution timing”.
When code is lazy, side effects happen not where you wrote them visually, but where the terminal operation occurs. As a result, you can get “late” logs, duplicated logs, or the feeling that the program “does nothing”. For learning purposes, println inside a chain is useful, but in production style it’s better to keep transformations as pure as possible.
Mistake #4: blindly sorting “everything” just to get top-N.
sortedByDescending(...).take(n) is a convenient and readable pattern; you’ve already used it. But it’s important to understand: the entire list is sorted, and only then you take the first elements. Sometimes that’s fine, sometimes it’s the heaviest part of the report. Today we are not studying alternative top-N selection algorithms without a full sort, but you should learn to notice the fact “this sorts everything”.
Mistake #5: trying to solve the intermediate-collection problem where the real problem is extra steps.
Sometimes you do filter and then another filter with almost the same condition, or first map and then map again, even though you could have done it in one step. In such places Sequence can reduce the number of intermediate lists, but it won’t reduce the number of logical steps. Often the stronger improvement is simply to simplify the pipeline, for example, replacing map { ... }.filterNotNull() with mapNotNull { ... }.
GO TO FULL VERSION