Skip to content

Chapter 19 of 37

Iterators

Traverse and modify collections with Iterator, ListIterator, Iterable, and Spliterator.

30 minutes 10 quick checksBy Subha Prasad
Lesson 19 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Iterable supplies an Iterator, enabling enhanced for. An iterator is a cursor; call hasNext before next. Many iterators are fail-fast on unsupported structural changes, but this is bug detection rather than a concurrency guarantee.

Controlled removal

Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    if (iterator.next().isBlank()) {
        iterator.remove();
    }
}

Removing through the iterator keeps its expected modification state synchronized. ListIterator moves both directions and supports add, set, and index queries. forEachRemaining consumes remaining elements. Spliterator reports characteristics and can partition traversal for stream pipelines. Do not reuse exhausted iterators, assume stable order from unordered collections, or modify a collection concurrently without its documented mechanism. Prefer collection bulk methods or streams when manual cursor control adds no value.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes Iterator?
Which Java term matches this description: A cursor with hasNext, next, and optional remove operations.
Which statement best describes Iterable?
Which Java term matches this description: A source that can create an Iterator and support enhanced for.
Which statement best describes ListIterator?
Which Java term matches this description: A bidirectional List cursor that can add, set, and inspect indices.
Which statement best describes fail-fast iterator?
Which Java term matches this description: A best-effort cursor that detects unsupported structural modification.
Which statement best describes Spliterator?
Which Java term matches this description: A traversal abstraction designed to split work for parallel processing.

0 of 10 checks passed

Your progress is saved on this device.