Iterators

suggest change

An iterator is an object that hands out the elements of a collection one at a time. Every for loop over a list, set, map or custom container uses an iterator under the hood.

Most of the time you never touch iterators directly. You need them when you want to:

The Iterator and Iterable interfaces

The standard library defines a small family of interfaces in kotlin.collections:

public interface Iterator<out T> {
    public operator fun next(): T
    public operator fun hasNext(): Boolean
}

public interface MutableIterator<out T> : Iterator<T> {
    public fun remove()
}

public interface ListIterator<out T> : Iterator<T> {
    fun hasPrevious(): Boolean
    fun previous(): T
    fun nextIndex(): Int
    fun previousIndex(): Int
}

public interface MutableListIterator<T> : ListIterator<T>, MutableIterator<T> {
    fun set(element: T)
    fun add(element: T)
}

public interface Iterable<out T> {
    public operator fun iterator(): Iterator<T>
}

The contract is simple:

An Iterable is something that can produce iterators. List, Set and every other Collection is an Iterable. A Map is not, but it has an iterator() extension over its entries.

The important difference: an Iterable can be traversed many times because every call to iterator() returns a fresh iterator. An Iterator is single-use: once it reaches the end, it stays there.

How a for loop uses an iterator

This loop:

val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}

is compiled to roughly this:

val iterator = fruits.iterator()
while (iterator.hasNext()) {
    val fruit = iterator.next()
    println(fruit)
}

Output (both versions):

apple
banana
cherry

There are two exceptions where the compiler doesn't create an iterator object: loops over arrays (Array<T>, IntArray, ...) and loops over number ranges and progressions (0..9, 0 until n, 10 downTo 0 step 2) are compiled to plain indexed loops. So for (i in 0 until n) is as fast as a C-style loop.

Using an iterator directly

Because an iterator remembers its position, you can consume part of a collection and continue later:

fun main() {
    val lines = listOf("name,age", "Ann,31", "Bob,27")
    val iter = lines.iterator()

    val header = iter.next()
    println("Header: $header")

    // the rest of the elements
    for (line in iter) {
        println("Row: $line")
    }
    println("More? ${iter.hasNext()}")
}

Output:

Header: name,age
Row: Ann,31
Row: Bob,27
More? false

for (line in iter) works on an Iterator because the standard library defines operator fun <T> Iterator<T>.iterator(): Iterator<T> = this.

Iterators also shine when you walk two collections at different speeds. A classic example is merging two sorted lists, which can't be expressed with a single for loop:

fun <T> Iterator<T>.nextOrNull(): T? = if (hasNext()) next() else null

fun merge(a: List<Int>, b: List<Int>): List<Int> {
    val ia = a.iterator()
    val ib = b.iterator()
    val out = mutableListOf<Int>()
    var x = ia.nextOrNull()
    var y = ib.nextOrNull()
    while (x != null && y != null) {
        if (x <= y) {
            out += x
            x = ia.nextOrNull()
        } else {
            out += y
            y = ib.nextOrNull()
        }
    }
    // one of the lists is exhausted, copy the rest of the other
    x?.let { out += it }
    ia.forEach { out += it }
    y?.let { out += it }
    ib.forEach { out += it }
    return out
}

fun main() {
    println(merge(listOf(1, 4, 7), listOf(2, 3, 8, 9)))
}

Output:

[1, 2, 3, 4, 7, 8, 9]

nextOrNull() is our own helper; it only works for lists that don't contain null.

Removing elements with MutableIterator

Iterators of mutable collections are MutableIterators with a remove() method that deletes the element most recently returned by next():

fun main() {
    val numbers = mutableListOf(1, 2, 3, 4, 5, 6)
    val iter = numbers.iterator()
    while (iter.hasNext()) {
        if (iter.next() % 2 == 0) {
            iter.remove()
        }
    }
    println(numbers)

    val stock = mutableMapOf("apples" to 3, "pears" to 0, "plums" to 5)
    val entries = stock.iterator()
    while (entries.hasNext()) {
        if (entries.next().value == 0) entries.remove()
    }
    println(stock)
}

Output:

[1, 3, 5]
{apples=3, plums=5}

You must not modify a collection directly while a for loop is iterating over it. The JVM collections detect this and throw ConcurrentModificationException:

fun main() {
    val names = mutableListOf("Ann", "Bob", "Cid")
    try {
        for (name in names) {
            if (name == "Ann") names.remove(name)
        }
    } catch (e: ConcurrentModificationException) {
        println("Caught $e")
    }
}

Output:

Caught java.util.ConcurrentModificationException

Worse, the check is not guaranteed. If you remove "Bob" (the second-to-last element) instead, hasNext() returns false right after the removal, the loop ends silently and "Cid" is never visited.

In practice, iter.remove() is rarely needed. The bulk operations are shorter and do the same thing safely:

val numbers = mutableListOf(1, 2, 3, 4, 5, 6)
numbers.removeAll { it % 2 == 0 }        // [1, 3, 5]

val stock = mutableMapOf("apples" to 3, "pears" to 0)
stock.values.removeAll { it == 0 }      // {apples=3}

Use an explicit iterator when the decision to remove depends on state built up during the loop, or when you also need to break early.

ListIterator: moving in both directions

list.listIterator() returns a ListIterator that can also go backwards and report indexes. For a MutableList it is a MutableListIterator, which can replace (set) and insert (add) elements in place:

fun main() {
    val letters = mutableListOf("a", "b", "c")
    val li = letters.listIterator()
    while (li.hasNext()) {
        val s = li.next()
        if (s == "b") {
            li.add("b2")          // inserted after "b", not returned by next()
        } else {
            li.set(s.uppercase()) // replaces the element just returned
        }
    }
    println(letters)

    // li is now at the end, walk backwards
    while (li.hasPrevious()) {
        println("${li.previousIndex()}: ${li.previous()}")
    }
}

Output:

[A, b, b2, C]
3: C
2: b2
1: b
0: A

listIterator(index) starts at a given position, so list.listIterator(list.size) is a convenient way to iterate a list in reverse. For simple reverse iteration, list.asReversed() or for (i in list.indices.reversed()) are usually clearer.

Making your own class iterable

Implement Iterable<T> and your class works in for loops and gets all the collection extension functions (map, filter, first, sum, joinToString, ...) for free:

class Countdown(private val from: Int) : Iterable<Int> {
    override fun iterator(): Iterator<Int> = object : Iterator<Int> {
        private var current = from

        override fun hasNext() = current > 0

        override fun next(): Int {
            if (!hasNext()) throw NoSuchElementException()
            return current--
        }
    }
}

fun main() {
    val countdown = Countdown(3)
    for (n in countdown) {
        println(n)
    }
    println(countdown.map { it * 10 })
    println(countdown.sum())
    println(countdown.joinToString(" .. ", postfix = " liftoff!"))
}

Output:

3
2
1
[30, 20, 10]
6
3 .. 2 .. 1 liftoff!

Note that the state (current) lives in the iterator, not in Countdown. That's why countdown can be iterated four times. If you stored the position in the Iterable itself, the second loop would see nothing.

The for-loop operator convention

A for loop doesn't actually require the Iterable or Iterator interfaces. It only needs:

class Bits(private val value: Int) {
    operator fun iterator() = BitsIterator(value)
}

class BitsIterator(private var rest: Int) {
    operator fun hasNext() = rest != 0

    operator fun next(): Int {
        val bit = rest.takeLowestOneBit()
        rest = rest xor bit
        return bit
    }
}

fun main() {
    for (bit in Bits(0b1011_0000)) {
        println(bit)
    }
}

Output:

16
32
128

The downside is that Bits is not an Iterable, so Bits(5).map { ... } doesn't compile. Prefer implementing Iterable<T> for your own classes.

The convention is most useful with extension functions: you can make a class you don't control loopable. The DOM API returns a NodeList, which has getLength() and item(i) but isn't iterable. One extension fixes that:

import javax.xml.parsers.DocumentBuilderFactory
import org.w3c.dom.Node
import org.w3c.dom.NodeList

operator fun NodeList.iterator(): Iterator<Node> = object : Iterator<Node> {
    private var i = 0
    override fun hasNext() = i < length
    override fun next(): Node =
        if (i < length) item(i++) else throw NoSuchElementException()
}

fun main() {
    val xml = "<books><book>Dune</book><book>Emma</book><book>Ulysses</book></books>"
    val doc = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .parse(xml.byteInputStream())

    for (node in doc.getElementsByTagName("book")) {
        println(node.textContent)
    }
}

Output:

Dune
Emma
Ulysses

See Operator functions for other operators you can overload.

Writing iterators with the iterator { } builder

Hand-written iterators need explicit state, which gets awkward for anything non-trivial, like traversing a tree. The iterator { } builder lets you write the traversal as ordinary code and yield each element. Execution suspends at every yield and resumes when the caller asks for the next element:

class TreeNode<T>(
    val value: T,
    val left: TreeNode<T>? = null,
    val right: TreeNode<T>? = null,
) : Iterable<T> {
    // in-order traversal: left subtree, node, right subtree
    override fun iterator(): Iterator<T> = iterator {
        left?.let { yieldAll(it) }
        yield(value)
        right?.let { yieldAll(it) }
    }
}

fun main() {
    //        4
    //      /   \
    //     2     6
    //    / \   / \
    //   1   3 5   7
    val tree = TreeNode(
        4,
        TreeNode(2, TreeNode(1), TreeNode(3)),
        TreeNode(6, TreeNode(5), TreeNode(7)),
    )

    println(tree.toList())
    println(tree.filter { it % 2 == 0 })
    println(tree.first { it > 4 })
}

Output:

[1, 2, 3, 4, 5, 6, 7]
[2, 4, 6]
5

yieldAll accepts another Iterable, Iterator or Sequence, which is what makes the recursion so short. The iterator is lazy: first { it > 4 } stops the traversal as soon as it finds 5, and nodes 6 and 7 are never visited.

The builder is implemented with restricted suspending functions, but it is plain synchronous code: it doesn't need kotlinx.coroutines and doesn't involve threads. Inside the block you can only call yield and yieldAll, not other suspending functions like delay.

To turn an iterator-producing lambda into an Iterable without declaring a class, use the Iterable { } function:

fun <T> repeatEach(items: List<T>, times: Int): Iterable<T> = Iterable {
    iterator {
        for (item in items) {
            repeat(times) { yield(item) }
        }
    }
}

fun main() {
    val doubled = repeatEach(listOf("a", "b", "c"), 2)
    println(doubled.joinToString())
    println(doubled.count())   // a fresh iterator each time
}

Output:

a, a, b, b, c, c
6

The same builder is available as sequence { }, which returns a Sequence instead; see Sequences.

AbstractIterator: compute the next element on demand

Implementing hasNext() correctly is often the tricky part: to know if there is a next element you may have to compute it, and then you must remember it until next() is called. kotlin.collections.AbstractIterator handles that bookkeeping. You implement one method, computeNext(), which either calls setNext(value) or done():

class WordIterator(private val text: String) : AbstractIterator<String>() {
    private var pos = 0

    override fun computeNext() {
        // skip non-letters
        while (pos < text.length && !text[pos].isLetter()) pos++
        if (pos >= text.length) {
            done()
            return
        }
        val start = pos
        while (pos < text.length && text[pos].isLetter()) pos++
        setNext(text.substring(start, pos))
    }
}

fun main() {
    for (word in WordIterator("Hello, world! How are you?")) {
        println(word)
    }

    val words = WordIterator("one two three four")
    println(words.next())
    println(words.hasNext())
    println(words.hasNext())   // safe to call repeatedly
    println(words.asSequence().toList())
}

Output:

Hello
world
How
are
you
one
true
true
[two, three, four]

computeNext() is called lazily, only when hasNext() or next() needs a value, and AbstractIterator throws NoSuchElementException for you when next() is called after done().

Don't confuse it with Guava's com.google.common.collect.AbstractIterator, which has a similar idea but a different API (computeNext() returns the value or endOfData()).

Primitive iterators

Iterator<Int> boxes every element into a java.lang.Integer. For primitive arrays and ranges the standard library provides specialized abstract classes IntIterator, LongIterator, CharIterator, DoubleIterator, BooleanIterator and so on, with a non-boxing nextInt(), nextLong(), ... method:

fun main() {
    val arr = intArrayOf(10, 20, 30)
    val iter: IntIterator = arr.iterator()
    var total = 0
    while (iter.hasNext()) {
        total += iter.nextInt()   // no boxing
    }
    println(total)

    val chars: CharIterator = "abc".iterator()
    println(chars.nextChar())
}

Output:

60
a

You can subclass them to write your own allocation-free iterators. Since these are subclasses of Iterator<Int>, they also work everywhere a regular iterator is expected; in that case next() boxes the value returned by nextInt().

Useful iterator extensions

The standard library has a few extension functions that work directly on Iterator:

fun main() {
    val iter = listOf("header", "x", "y", "z").iterator()
    iter.next()                       // skip the header

    for ((index, value) in iter.withIndex()) {
        println("$index -> $value")
    }

    listOf(1, 2, 3).iterator().forEach { print("$it ") }
    println()

    val seq = listOf(1, 2, 3).iterator().asSequence()
    println(seq.map { it * 2 }.toList())
    try {
        seq.toList()
    } catch (e: IllegalStateException) {
        println(e.message)
    }
}

Output:

0 -> x
1 -> y
2 -> z
1 2 3 
[2, 4, 6]
This sequence can be consumed only once.

Note that withIndex() counts from where the iterator currently is, not from the start of the list. And because an iterator can't be rewound, asSequence() returns a sequence that throws if you try to iterate it a second time, instead of silently returning nothing.

To get all of map, filter and friends on an iterator, convert it with asSequence(), or collect it with iter.asSequence().toList().

Java interop

Kotlin's Iterator and MutableIterator are both mapped to java.util.Iterator at runtime, and Iterable to java.lang.Iterable. Any Java collection or Java class implementing Iterable works in Kotlin for loops unchanged, and any Kotlin Iterable can be passed to Java code.

When a Java method returns java.util.Iterator<T>, Kotlin sees it as a platform type (Mutable)Iterator<T!>!. Kotlin lets you call remove() on such an iterator, but if the underlying collection is unmodifiable (for example Collections.unmodifiableList(...) or List.of(...)), it throws UnsupportedOperationException at runtime. The read-only Iterator type is a compile-time view only; the object behind it is still a java.util.Iterator.

Older Java APIs use java.util.Enumeration. The standard library adds an iterator() operator and toList() for it:

import java.util.StringTokenizer

fun main() {
    for (token in StringTokenizer("to be or not")) {
        print("[$token]")
    }
    println()

    val tokens = StringTokenizer("a:b:c", ":").toList()
    println(tokens)
}

Output:

[to][be][or][not]
[a, b, c]

StringTokenizer implements Enumeration<Object>, so token has type Any.

To go the other way and give Java code an Enumeration, use java.util.Collections.enumeration(list).

Iterators vs sequences

Iterators and sequences are closely related: a Sequence<T> is basically a lazily evaluated Iterable<T>, with an iterator() method and a different set of extension functions.

Common mistakes

Creating a new iterator in the loop condition. Each call to iterator() starts from the beginning, so this is an infinite loop:

// WRONG: infinite loop, always looks at the first element
while (list.iterator().hasNext()) {
    println(list.iterator().next())
}

Store the iterator in a variable once.

Storing iteration state in the Iterable. If iterator() returns this, or the position is a field of the Iterable, the object can only be traversed once and two nested loops over it interfere with each other. Always return a new iterator object.

Not throwing from next(). next() must throw NoSuchElementException when there are no more elements, not return null or a sentinel value. Code like first() relies on the contract.

hasNext() with side effects. Callers may call hasNext() any number of times before next(). If hasNext() advances or reads input, elements get skipped. Use AbstractIterator or the iterator { } builder to avoid writing this logic by hand.

Modifying a collection during a for loop. Use iter.remove(), removeAll { }, or build a new collection with filter instead of calling list.remove() inside for (x in list).

For looping basics see Looping over iterables and Iterating over a Map in Kotlin.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents