Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 134 ยท Collections

Sequences

Learn Kotlin sequences: lazy evaluation, asSequence, generateSequence, the sequence builder with yield, intermediate versus terminal operations, and when sequences beat lists.

A normal Kotlin collection operation is eager: list.filter { ... } runs immediately, walks the whole list and returns a complete new list. Chain three operations and you get three passes and two throw-away lists. For small data that is perfectly fine, and usually the clearest option. For huge data, or when you only need the first few results, or when the data never ends, you want the opposite approach: lazy evaluation, where nothing happens until a result is demanded and each element travels through the whole chain on its own.

Kotlin's name for a lazy collection is a sequence (Sequence<T>). In this lesson you learn how sequences work step by step, how to create them (including infinite ones), which operations are lazy and which are not, and when a sequence is the wrong choice. It builds on Collection Transformations and uses the same function names.

Eager versus lazy, side by side

The best way to understand a sequence is to watch the order of work. This program prints a line whenever filter or map touches an element:

Kotlin Watching the order of work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The list version prints filter 1 through filter 6, then map 2, map 4, map 6, and finally 20. Every stage finishes with all elements before the next stage starts, even though we only wanted the first result.

The sequence version prints just filter 1, filter 2, map 2 and 20. Element 1 goes through the filter and is rejected. Element 2 goes through the filter, then through the map, and arrives at first(), which says "that is enough". Elements 3 to 6 are never touched. That is the whole idea:

  • Eager (list): stage by stage. Each stage processes all elements and creates a full intermediate list.
  • Lazy (sequence): element by element. Each element runs through all stages before the next one starts, and no intermediate collection is built.

You create a sequence from any collection with asSequence(), from values with sequenceOf(...), from a range with (1..n).asSequence(), or from text with lineSequence() and splitToSequence().

Intermediate and terminal operations

A sequence chain has two kinds of operations:

  • Intermediate operations (map, filter, take, drop, takeWhile, flatMap, distinct, zip, windowed, chunked, onEach, ...) return another sequence. They do no work by themselves; they only describe what should happen.
  • Terminal operations (toList, first, sum, count, any, fold, joinToString, forEach, ...) return an ordinary value and start the computation.

Without a terminal operation, nothing runs at all:

Kotlin Laziness and re-running

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You first see nothing happened yet. Only then does toList() trigger map 1, map 2, map 3 and print [2, 4, 6]. After again the whole thing runs a second time, because a sequence does not remember results; it recomputes them on every terminal call. That is cheap for pure calculations, but expensive or wrong if the source has side effects, such as reading from a file or a network. If you need the results again, store them with toList() once.

A very common beginner bug: building a sequence chain and forgetting the terminal operation. list.asSequence().map { save(it) } does nothing: save is never called. Finish with toList(), forEach { } or another terminal operation.

Creating sequences

There are three general ways to produce a sequence from nothing: generateSequence, the sequence { } builder, and ranges or collections.

Kotlin generateSequence and the sequence builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [1, 2, 3, 4, 5], [7, 14, 21], [1, 3, 9, 27, 81, 243, 729], [kotlin, kotli, kotl, kot, ko, k], [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], 1597 and [start, a, b, x, y].

  • generateSequence(seed) { next } starts with a seed and applies the lambda to the previous element to get the next one. The sequence ends when the lambda returns null. That explains the powers example: after 729 (which is above 500) the lambda returns null. If the lambda never returns null, the sequence is infinite, like naturals.
  • sequence { ... } is a builder in which you call yield(value) to emit one element and yieldAll(...) to emit many. The code inside runs like a normal function, loops and variables included, but it pauses at every yield and resumes only when the consumer asks for the next element. This is how the Fibonacci sequence manages while (true) without hanging: take(10) asks for ten values, and the builder pauses forever after the tenth. The mechanism is a suspend function; you meet the idea properly in Suspend Functions.
  • Infinite sequences are fine as long as a lazy operation limits them (take, takeWhile, first { }, find).

Be careful with infinite sequences, because a terminal operation that needs every element never finishes. naturals.toList(), naturals.count(), naturals.sum() and naturals.map { it * 2 }.toList() would run until memory or patience runs out. The compiler cannot warn you.

The runner on this page stops programs after ten seconds, so we do not run an infinite toList() here. In your own code it would either hang forever or end in an OutOfMemoryError when the list outgrows memory. Always put take, takeWhile or a search such as first { } somewhere before the terminal operation.

The standard operations

Almost every collection function you know exists for sequences, with the same names and meaning. Some stay lazy; some must see every element first.

Kotlin A tour of sequence operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are [4, 16, 36, 64], [1, 2, 3], [7, 8], [1, 2, 3], [1, 2, 3], [[1, 2, 3], [4, 5, 6], [7, 8]], [(1, 2), (2, 3)], [1, -1, 2, -2], [1, 4, 7], then 36, 3, true, 36, 1|2|3|4|5|6|7|8, {1=[1, 4, 7], 2=[2, 5, 8], 0=[3, 6]} and ([5, 6, 7, 8], [1, 2, 3, 4]).

Two groups to keep apart:

  1. Lazy and element by element: map, filter, take, drop, takeWhile, flatMap, zip, withIndex, windowed, chunked. These can run on infinite sequences. In the last two, the "window" or "chunk" is built as a small list, but the sequence of windows is still lazy.
  2. Stateful operations that must see everything first: sorted, sortedBy, distinct (needs to remember seen elements), groupBy and partition (these are terminal and return collections). sorted() collects all elements into a list, sorts it, and hands them out again. So infiniteSequence.sorted() hangs, and placing sorted() early in a chain destroys the laziness benefit for everything before it.

Because the order of stages matters, put the operations that discard the most elements first. filter before map means you transform fewer elements; take as early as possible means you stop sooner.

Sequences are iterated one at a time

A sequence is just an Iterator factory. You can step through it by hand, which shows the pausing of the sequence { } builder:

Kotlin The builder pauses at yield

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output interleaves producer and consumer: producing 1, 1, between, producing 2, 2. The block does not run ahead; it produces one value, freezes, and continues from the same spot on the next next().

What sequences do not have

A sequence has no size and no indexes, because it may not have an end. Trying to treat it like a list fails at compile time:

Kotlin Sequences have no index or size (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

There are two errors: main.kt:3:16: error: no 'get' operator method providing array access. and main.kt:4:17: error: unresolved reference 'size' on receiver of type 'Sequence<Int>'. Use elementAt(1) (which walks to the position) or count() (which walks the entire sequence), or convert with toList() if you need random access.

Many sequences can be iterated several times, but not all of them. A sequence made from an Iterator or one marked with constrainOnce() can be consumed only once:

Kotlin Consuming a sequence twice (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first toList() prints [1, 2, 3]. The second one crashes with Exception in thread "main" java.lang.IllegalStateException: This sequence can be consumed only once. Sequences from files or network streams often have this property, since the source cannot be rewound. Treat a sequence as a stream you read once unless you know its source is repeatable.

When sequences pay off, and when they do not

Sequences are not a faster List. For small collections the extra objects and indirection of a lazy chain can make them slower than plain lists. They win in specific situations:

Kotlin Where sequences help

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both versions give the same answer: true and [6, 12, 18, 24, 30]. The list version builds a list of about 666,000 filtered numbers and another of the same length for map, only to keep five of them. The sequence version stops after producing five. Next come [49, 196, 441], the sum 1000001000000 of doubled numbers (a Long, so there is no overflow), and 40, the sum of the first two valid numbers.

Use a sequence when:

  • The source is large and the chain has several steps (fewer intermediate lists).
  • You only need part of the result (first, take, find, any): early exit saves work.
  • The source is infinite or generated on demand: counters, Fibonacci numbers, paginated data.
  • You read lines of a big file or a stream and process them one by one (lineSequence(), or File.useLines { } in Files and IO).

Stay with plain lists when:

  • The collection is small (hundreds of elements), or the chain has one operation.
  • You need the result several times, or random access, or the size.
  • The chain contains sorted, distinct or groupBy early on, which force full evaluation anyway.
  • The chain is readable and fast enough already. Measure before optimising.

One more point of design: lambdas passed to list operations are inline, so there is no function-object overhead; a sequence stores each lambda in an object. See Inline Functions for why. That is another reason not to reach for asSequence() by habit.

Real-world examples

Kotlin Primes, Collatz and text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see [2, 3, 5, 7, 11, 13, 17, 19], 112 (the Collatz chain starting at 27 has 112 numbers), 9232 (its peak), [[a, b], [c, d], [e]], [5, 5], [1, 3, 9] and [1, 2, 3]. Note how none { } inside the prime test is itself a short-circuiting terminal operation on a range, and how the Collatz sequence ends naturally by returning null.

Pitfalls

  • Forgetting the terminal operation: nothing runs.
  • Infinite sequences with an unbounded terminal operation (toList, count, sum, sorted) hang or run out of memory.
  • Side effects in lazy lambdas run at unexpected times and possibly several times (once per terminal call). Keep lambdas pure.
  • Re-iterating a one-shot sequence throws IllegalStateException.
  • Putting sorted() or distinct() early removes the laziness for the rest.
  • Using sequences for tiny lists adds overhead without benefit.
  • Asynchronous work does not belong in a sequence; use coroutines and flows, which are the asynchronous cousin of sequences.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does listOf(1, 2, 3).asSequence().map { println(it); it * 2 } print when executed on its own line?

    map on a sequence is an intermediate operation. Without a terminal operation like toList(), the lambda never runs.
  2. 2. In a sequence chain filter { } .map { } .first(), in what order are elements processed?

    Sequences process one element at a time through the whole chain, so first() can stop early.
  3. 3. What ends a generateSequence(1) { ... } sequence?

    A null result from the next-element lambda ends the sequence. Without it the sequence is infinite.
  4. 4. Which operation is a bad idea on an infinite sequence like generateSequence(1) { it + 1 }?

    sorted() must collect every element before it can emit the first, so it never finishes on an infinite sequence.
  5. 5. Which situation is the best fit for a sequence rather than a list?

    Sequences shine for big inputs, several steps and early exits. They have no indexes or size.

Summary

  • A Sequence evaluates lazily: elements flow one at a time through the whole chain, and nothing runs until a terminal operation (toList, first, sum, count, ...) is called.
  • Create sequences with asSequence(), sequenceOf(), generateSequence(seed) { next } (ends on null) or the sequence { yield(...) } builder, which pauses at each yield.
  • Intermediate operations (map, filter, take, ...) are lazy; sorted, distinct and groupBy need to see all elements first.
  • Sequences have no size or indexing, are recomputed on every terminal call, and some can be consumed only once.
  • Use them for large data, several steps, early exits and infinite or generated data; use plain lists for small data and repeated access.
  • Always bound infinite sequences with take, takeWhile or a search before a terminal operation.

Next: Pairs, Triples and Destructuring