Kotlin

Sequences — Lazy Collections

admin by @admin ADMIN
3h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
A `List` materializes every intermediate `map`/`filter` result. A `Sequence` processes ONE element through the whole pipeline at a time — better for big inputs or short-circuiting (`first`, `take`).
Kotlin
Raw
fun main() {
    // Eager — every step builds a new List
    val list = (1..1_000_000)
        .toList()
        .map    { it * 2 }                    // allocates List<Int> of 1M elements
        .filter { it % 3 == 0 }               // allocates again
        .take(10)                             // only 10 wanted — but already did all the work above
    println(list.size)                        // 10

    // Lazy — each element flows through the full pipeline before the next starts
    val seq = (1..1_000_000).asSequence()
        .map    { it * 2 }
        .filter { it % 3 == 0 }
        .take(10)                             // stops as soon as 10 are produced
        .toList()
    println(seq.size)                         // 10 — but did vastly less work

    // Infinite sequences with generateSequence
    val fibs = generateSequence(0 to 1) { (a, b) -> b to (a + b) }
        .map { it.first }
        .take(15)
        .toList()
    println(fibs)                             // [0, 1, 1, 2, 3, 5, 8, 13, 21, ...]

    // Rule of thumb: use Sequence when the chain is LONG or the input is HUGE.
    // For small lists, plain List + .map { ... } is simpler and JIT-friendly.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.