Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Iterators and traversal in Java

Iterators and traversal in Java: Iterable supplies the Iterator used by enhanced for; Iterator advances with hasNext/next and may remove the last returned element through optional remove.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

iterators

Iterable supplies the Iterator used by enhanced for; Iterator advances with hasNext/next and may remove the last returned element through optional remove.

Use Iterator.remove for in-place collection filtering, ListIterator for bidirectional list editing, and Spliterator to partition work for Stream.

Mutating a collection outside its iterator during traversal is generally unspecified or yields best-effort ConcurrentModificationException, not synchronization.

next after exhaustion throws NoSuchElementException, remove is allowed once per next, concurrent collections may be weakly consistent, and snapshot iterators omit later changes.

Iterator removes the even values, ListIterator inserts 10 after 1, and both Spliterator parts together preserve [1, 10, 3].

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var values = new ArrayList<>(List.of(1, 2, 3, 4));
        for (var iterator = values.iterator(); iterator.hasNext();) {
            if (iterator.next() % 2 == 0) iterator.remove();
        }
        System.out.println(values);

        var listIterator = values.listIterator();
        while (listIterator.hasNext()) {
            if (listIterator.next() == 1) listIterator.add(10);
        }
        System.out.println(values);

        var right = values.spliterator();
        var left = right.trySplit();
        var traversed = new ArrayList<Integer>();
        if (left != null) left.forEachRemaining(traversed::add);
        right.forEachRemaining(traversed::add);
        System.out.println(traversed);
    }
}

Result

[1, 3]
[1, 10, 3]
[1, 10, 3]

Iterator removes the even values, ListIterator inserts 10 after 1, and both Spliterator parts together preserve [1, 10, 3].

Sources