CodeGym /Courses /Kotlin SELF /Sequence: laziness and terminal operations

Sequence: laziness and terminal operations

Kotlin SELF
Level 25, Lesson 2
Available

1. Why you need Sequence

When you start writing chains like filter → map → filter → map, you get that nice feeling that the code now resembles a normal human thought: “take the expenses, keep only the ones you need, transform them, compute the result.” But chains on regular collections have a hidden side: many steps create intermediate collections “right now.” On small data this is not a problem at all, but on large data it can turn into extra work and extra memory usage. That is exactly where Sequence comes in: it lets you describe a chain so computations happen on demand — when we actually request the result.

Important: Sequence is not a “magic speed-up button,” it is a different execution model. Today our goal is to learn to understand when a chain actually runs, and why sometimes it feels like the program “did nothing.”

What Sequence is and how to get it

If a List is like a ready plate of pasta (you can eat it right away, count the noodles, sort the noodles, argue with friends that the noodles are not sorted), then a Sequence is more like a recipe: “take ingredients, strain, chop, saute…”. A recipe by itself does not fill you up. What fills you up is the moment you start cooking.

From Kotlin’s point of view, Sequence<T> is an interface you can iterate (via an Iterator). That means Sequence is great for a “left-to-right pass,” but it does not promise convenient random access by index (it’s not a list).

The most important rule of the day sounds like this:

Sequence is lazy: intermediate steps are not executed immediately. They run only when a terminal operation appears — one that asks for a result.

How to put a collection into lazy mode with asSequence()

When we have a collection and we want to apply the lazy model to it, we typically do this:

fun main() {
    val xs = listOf(1, 2, 3, 4)

    val ys = xs.asSequence()
        .filter { it % 2 == 0 }
        .map { it * 10 }
        .toList()

    println(ys) // [20, 40]
}

Notice the toList() at the end: this is not “cosmetic,” it’s the moment when we say: “OK, Kotlin, now actually compute and give me a regular list.”

In Kotlin docs and examples, they usually show exactly this pattern: a chain on a Sequence, then toList() to obtain the final collection.

3. Intermediate and terminal operations

Now comes a key idea that saves hours of debugging and a couple of nerve cells (which, as everyone knows, are immutable for programmers too).

Intermediate operations are those that return a Sequence again and continue building the “pipeline”: map, filter, distinct, sorted (yes, sequences have variants), take, drop, and many others. They are not required to perform computations right now — they only add a “stage to the pipeline.”

Terminal operations are those that request a result: toList(), toSet(), count(), first() / firstOrNull(), find(), fold(), sum() (in different forms), etc. A terminal operation starts execution: elements begin flowing through the pipeline until the result is produced.

For convenience, let’s summarize this in a table. It is not “complete for the entire standard library,” but it provides the correct mental model.

Operation On a Sequence, usually this is… Returns Starts computation?
map { ... }
intermediate
Sequence<R>
no
filter { ... }
intermediate
Sequence<T>
no
take(n)
intermediate
Sequence<T>
no
toList()
terminal
List<T>
yes
count()
terminal
Int
yes
firstOrNull()
terminal
T?
yes
fold(initial) { ... }
terminal
R
yes

If you keep exactly this table in mind, most of the mysteries around Sequence disappear.

4. Why “nothing happened”

This is a classic situation: a student writes a chain expecting something to execute inside filter or map right away, then runs the program — and… silence. It feels like Kotlin ignored your code. Kotlin can do a lot, but it still does not have telepathy: you simply did not request the result.

Let’s look at an example where we explicitly print inside filter and map to “see the execution.”

fun main() {
    val xs = listOf(1, 2, 3, 4)

    val seq = xs.asSequence()
        .filter { x ->
            println("filter: $x")
            x % 2 == 0
        }
        .map { x ->
            println("map: $x")
            x * 10
        }

    println("before toList")          // before toList
    val ys = seq.toList()
    println("after toList: $ys")      // after toList: [20, 40]
}

The output order matters here. First you will see "before toList", and only then will "filter: ..." and "map: ..." start printing, because before toList() the chain was only “described.”

And now — the “painful” example where the terminal operation is missing:

fun main() {
    val xs = listOf(1, 2, 3)

    xs.asSequence()
        .filter { x ->
            println("check: $x")
            x > 1
        }

    println("done") // done
}

The only output will be "done". The "check: ..." lines will not appear at all, because you created a Sequence, added an intermediate step filter, and then… threw it all into the trash. Formally, you built a pipeline and immediately went home without turning on the machine.

5. Early terminal operations and materialization

In this section it is important to carefully land the idea: a terminal operation starts execution, but it does not always need to process everything to the end. For example, toList() really collects all result elements, but firstOrNull() can stop at the first matching element.

This is not “optimization for optimization’s sake,” it is simply the meaning of the operation: if I asked for “the first matching one,” why would I iterate further?

Let’s look at a demonstration:

fun main() {
    val xs = listOf(1, 2, 3, 4, 5)

    val firstBigEven = xs.asSequence()
        .filter { x ->
            println("filter: $x")
            x % 2 == 0
        }
        .map { x ->
            println("map: $x")
            x * 10
        }
        .firstOrNull { value ->
            println("firstOrNull predicate: $value")
            value >= 30
        }

    println("result: $firstBigEven") // result: 40
}

Notice: the sequence does not have to process all elements up to 5. It will iterate until it finds an answer that satisfies firstOrNull { ... }.

toList() as materialization

It helps to say in plain English that toList() is like a “cook it and plate it” button. While you are in Sequence, you have a recipe and a pipeline. After toList(), you get a concrete List that you can index into, print, sort with ordinary approaches, pass where a List is expected, and generally live your normal life.

A “typical” back-and-forth example:

fun main() {
    val raw = listOf("  food:120  ", " taxi:250", "food:80")

    val cleaned = raw.asSequence()
        .map { it.trim() }
        .filter { it.isNotEmpty() }
        .toList()

    println(cleaned) // [food:120, taxi:250, food:80]
}

After toList() you are back in a regular list. And that is fine: in real programs, Sequence is often used as an “internal processing mode,” and you return regular collections or final numbers/strings to the outside.

6. Sequence in the BudgetBuddy app

Now we will carefully continue our training console app (let’s conventionally call it BudgetBuddy): it stores expenses and can build reports. Let me remind you of the data-structure idea without OOP: expenses can be stored as Triple(category, amount, note). This is not “ideal,” but for the current stage of the course, it is enough.

Let’s start with a small data stub:

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
        Expense("food", 80, "coffee"),
        Expense("books", 500, "kotlin"),
    )

    println(expenses.size) // 4
}

Category report example for "food"

Let’s make a chain that:

first keeps only "food", then turns an expense into a report line, and at the end collects a list of strings.

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
        Expense("food", 80, "coffee"),
    )

    val lines = expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }
        .map { (cat, amount, note) -> "$cat: $amount ($note)" }
        .toList()

    println(lines) // [food: 120 (lunch), food: 80 (coffee)]
}

Why is Sequence even appropriate here if there is little data? The honest answer: at this scale, it is not particularly important. But it is a great way to get used to the model “intermediate steps do not execute until there is a terminal one.”

“I added filter, but nothing changed”

One of the common mistakes in BudgetBuddy reports looks like this: a student builds a Sequence, expects it to somehow “update the list on its own,” but the chain is not stored anywhere and not materialized.

Here is an example of the wrong approach (it compiles and does nothing — just like some students on Monday morning):

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = mutableListOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
    )

    expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }

    println(expenses.size) // 2
}

Why 2 and not 1? Because filter on a Sequence does not “remove from the list,” it creates a new sequence (a selection recipe). You did not use it and did not request the result.

The correct option is to obtain the result and explicitly use it:

typealias Expense = Triple<String, Int, String>

fun main() {
    val expenses = listOf(
        Expense("food", 120, "lunch"),
        Expense("taxi", 250, "airport"),
    )

    val foods = expenses.asSequence()
        .filter { (cat, _, _) -> cat == "food" }
        .toList()

    println(foods.size) // 1
}

7. Sequence and side effects

When you see laziness, there is a temptation to use println inside map/filter not only for learning, but also “for real”: logging, counting something in an external variable, updating state. This is possible, but it very quickly turns into a trap.

The problem is that in a lazy model you can no longer “intuitively” say when exactly your code will run. It will run when someone requests the result, and exactly as many times as actually needed. If you accidentally call a terminal operation twice (for example, toList() twice on the same sequence built again), your side effect will also happen twice. And then you will think Kotlin “duplicates elements,” while in reality your logic is duplicating.

So a good habit is this: keep map/filter pure (no side effects), and if you need to “see what’s going on,” do it either temporarily via println, or as a separate step that does not affect the meaning of the program.

8. Typical mistakes when working with Sequence

Error #1: no terminal operation — “nothing happened.”
This is the most popular trap. You build asSequence().filter { ... }.map { ... }, and then expect the list to have already “become different.” But Sequence is a lazy recipe, not a ready result. You need a terminal step: toList(), count(), firstOrNull(), fold(), and so on.

Error #2: expecting Sequence to “change the original collection.”
filter and map do not remove items from your MutableList and do not rewrite it. They create a new result (or a new “pipeline”). If you need to actually delete items — that is a different task and different code, and Sequence is not a magic broom here.

Error #3: side effects inside map/filter and the confusion that follows.
When inside map you print something, increment a counter, write to a file, or change an external variable, you tie the meaning of the program to the moment of evaluation. In a lazy model, the moment of evaluation depends on the terminal operation, and the code becomes harder to predict and debug.

Error #4: turning Sequence into a “religion.”
Sometimes a student starts inserting asSequence() into every chain because it looks “professional.” On small data this often gives no benefit, and sometimes even hurts readability: it becomes harder to see where exactly the result is obtained. It is much better to keep a simple rule in mind: Sequence is useful when you care about lazy execution of a chain; in other cases, regular operations on List remain an excellent, readable tool.

Error #5: forgetting that the result is needed as a collection and not materializing it.
A very common story in reports: you built a Sequence<String>, and then you try to print it as if it were a List<String>, or pass it where a list is expected. The solution is simple: add toList() (or another terminal step) at the end and work with the final value.

1
Task
Kotlin SELF, level 25, lesson 2
Locked
Bonus filter
Bonus filter
1
Task
Kotlin SELF, level 25, lesson 2
Locked
Lazy pipeline
Lazy pipeline
1
Task
Kotlin SELF, level 25, lesson 2
Locked
Quick search
Quick search
1
Task
Kotlin SELF, level 25, lesson 2
Locked
Expense cleanup
Expense cleanup
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION