Collections vs sequences

Kotlin language Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

How many times is map called?

fun main() {
    var calls = 0
    val first = (1..1_000).asSequence()
        .map { calls++; it * 2 }
        .first { it > 10 }
    println("$first $calls")
}
Options
Hint 1 of 1

Does map run for every element before first checks?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 12 6

Correct. Elements go one at a time; map runs for 1 to 6, and 6*2 = 12 is the first above 10.

Why not the others?
  • B 12 1000. That's what a List chain would do: map everything first.
  • C 11 6. map doubles, so values are even.
  • D 2 1. 2 isn't greater than 10.

30-second answer

List operations like map and filter run eagerly: each step builds a full intermediate list. A Sequence runs lazily, element by element, through the whole chain, and stops as soon as a terminal operation like first or take has what it needs. Use sequences for long chains on large collections or when you stop early; lists are faster for small ones.

Practise saying it · 30 s. No recording, just a timer

Explain collections vs sequences.

Say your answer out loud, then check which of these points you covered:

  • Lists are eager with intermediate lists
  • Sequences are lazy, per element
  • Good for large chains and early exit
  • Lists are faster for small data

Deep dive

asSequence() converts; toList() ends the chain.

Sequences can be infinite with generateSequence.

Some operations, like sorted, still need all elements.

Flow is the asynchronous cousin of Sequence: also lazy, but suspending.

Common mistakes

  • Using sequences for tiny lists and adding overhead.
  • Forgetting the terminal operation, so nothing runs.
  • Assuming sorted on a sequence stays lazy.

Senior take & follow-ups

Give the element-by-element picture and the early-exit example.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's the relationship between Sequence and Flow?

    Show hint

    Both are lazy streams; Flow can suspend.

  2. Does take(3) process the whole source?

    Show hint

    On a sequence, no; it stops after three items pass.

Suggest a fix if something here is wrong or out of date.