Skip to content
Sequences
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Lists evaluate operations eagerly — each step produces a new intermediate list. For large data or chains where you only need part of the result, that's wasteful.

Sequence is the lazy counterpart: nothing runs until a terminal operation (toList, sum, find, count, etc.).

// Eager — creates an intermediate list at each step
val result = (1..1_000_000)
    .map { it * it }
    .filter { it % 7 == 0 }
    .take(5)

// Lazy — pulls only what's needed for take(5)
val lazy = (1..1_000_000).asSequence()
    .map { it * it }
    .filter { it % 7 == 0 }
    .take(5)
    .toList()    // forces evaluation

For short chains and small collections, List is fine. For long pipelines or huge sources (or infinite sources via generateSequence), reach for Sequence. Same API — just .asSequence() to switch in.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…