Skip to the workspace
Pebellslearn by building
Collections, Ranges and Sequences  ›  Capstone Project

Iterators and Sequences

Iterators 15 minAn iterator hands out a collection's elements one at a time with hasNext and next, and a sequence uses that one-at-a-time style to run a chain of operations lazily, doing work only when a result is requested.

kotlin / Iterators and Sequences

Explore each scene at your own pace.

01 · The rule

The rule

Iterators and Sequences

An iterator hands out a collection's elements one at a time with hasNext and next, and a sequence uses that one-at-a-time style to run a chain of operations lazily, doing work only when a result is requested.

Compare eager collection operations with a sequence consumed only as needed.

At closing time, the manager asks for "the first order today of more than 15 cups, after the promotion doubles them". There were thousands of orders. Doubling every single one to find the first match is wasteful. Iterators and sequences let Kotlin do only the work that is needed.

The rule

An iterator hands out one at a time; a sequence waits until asked.

Iterators. Every collection can give you an iterator, an object that walks through it:

val orders = listOf(2, 9, 4)
val iter = orders.iterator()
while (iter.hasNext()) {
    println(iter.next())    // 2, then 9, then 4
}

hasNext() asks "is there another?" and next() returns it and moves on. A for loop uses an iterator behind the scenes. A mutable collection's iterator can also remove() the current element, which is the safe way to delete while walking; removing from a list inside a plain for loop over it usually throws ConcurrentModificationException.

Sequences. Collection operations like map (change each element) and filter (keep some elements) are eager: each step processes the whole list and builds a new one. The braces hold a small function; it means "the current element".

Call asSequence() first and the chain becomes lazy: each element travels through all the steps, one at a time, and nothing happens until a terminal operation such as first(), toList() or count() asks for a result.

val orders = listOf(2, 9, 4, 12, 7)
val firstBig = orders.asSequence()
    .map { it * 2 }
    .first { it > 15 }
println(firstBig)   // 18 — only 2 and 9 were doubled

Without asSequence(), all five orders are doubled first, and then the search starts.

Sequences can even be endless: generateSequence(1) { it * 2 }.take(5).toList() gives [1, 2, 4, 8, 16].

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.