TExcelTAD
Home › Kotlin › Kotlin Sequences

Kotlin Sequences

Collection operations like map and filter are eager: each step processes the whole collection and builds a new list before the next step starts. Sequences are lazy: elements flow through the whole chain one at a time, and nothing is computed until you ask for a result. That can save a lot of work — and makes infinite data streams possible.

Eager vs. lazy, side by side

kotlin · try it yourself
fun main() {
    val words = listOf("apple", "kiwi", "banana", "fig", "cherry")

    println("-- List (eager) --")
    val a = words
        .filter { println("filter $it"); it.length > 3 }
        .map { println("map $it"); it.uppercase() }
        .first()
    println(a)

    println("-- Sequence (lazy) --")
    val b = words.asSequence()
        .filter { println("filter $it"); it.length > 3 }
        .map { println("map $it"); it.uppercase() }
        .first()
    println(b)
}
-- List (eager) --
filter apple
filter kiwi
filter banana
filter fig
filter cherry
map apple
map kiwi
map banana
map cherry
APPLE
-- Sequence (lazy) --
filter apple
map apple
APPLE

The list version filtered all five words and mapped four, only to use the first result. The sequence processed one element and stopped.

Intermediate and terminal operations

Kind Examples Returns
intermediate (lazy) map, filter, take, drop, distinct, sortedBy another Sequence
terminal (triggers work) toList, first, count, sum, forEach, joinToString a value or collection

Without a terminal operation, nothing runs at all:

kotlin · try it yourself
fun main() {
    val seq = sequenceOf(1, 2, 3).map { println("computing $it"); it * 2 }
    println("Sequence created, nothing computed yet")
    println(seq.toList())
}
Sequence created, nothing computed yet
computing 1
computing 2
computing 3
[2, 4, 6]

Infinite sequences

Because sequences are lazy, they can be infinite — you just have to take a finite part.

kotlin · try it yourself
fun main() {
    val powersOfTwo = generateSequence(1) { it * 2 }
    println(powersOfTwo.take(10).toList())

    val fib = generateSequence(0 to 1) { (a, b) -> b to a + b }.map { it.first }
    println(fib.take(12).joinToString())

    println(generateSequence(1) { it + 1 }.map { it * it }.first { it > 200 })
}
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
225

generateSequence(seed) { next } keeps producing values until the lambda returns null. That makes it great for walking linked structures:

kotlin · try it yourself
fun main() {
    val collatz = generateSequence(7) { n ->
        when {
            n == 1 -> null
            n % 2 == 0 -> n / 2
            else -> 3 * n + 1
        }
    }
    println(collatz.toList())
    println("Steps: ${collatz.count() - 1}")
}
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Steps: 16

The sequence builder

sequence { … } lets you produce values with yield, pausing between them — a gentle preview of coroutines:

kotlin · try it yourself
fun main() {
    val primes = sequence {
        var n = 2
        while (true) {
            if ((2..<n).none { n % it == 0 }) yield(n)
            n++
        }
    }
    println(primes.take(10).toList())
}
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

When to use sequences

Use a List when… Use a Sequence when…
the collection is small or medium the collection is large and the chain has many steps
you need the intermediate results anyway you only need part of the result (first, take)
you access by index the data is infinite or generated on demand

Tip: Sequences have a small per-element overhead, so for a handful of elements a plain list chain is often just as fast. Measure before "optimising", and remember that sorting in a sequence still needs to look at every element.

Test yourself

When does a sequence perform its map and filter steps?

  1. Immediately when declared
  2. When a terminal operation like toList() is called
  3. Never
  4. At compile time

Which function creates an infinite sequence from a seed and a next-value function?

  1. sequenceOf
  2. generateSequence
  3. listOf
  4. repeat

How do you turn a List into a Sequence?

  1. list.toSequence()
  2. list.asSequence()
  3. Sequence(list)
  4. list.lazy()