Files
design-patterns/03-behavioral/iterator

Iterator Design Pattern — Java Example

Pattern: Behavioral → Iterator Article: https://ankurm.com/iterator-design-pattern-java/

What this example shows

A BookShelf stores Book objects in an internal ArrayList but never exposes it. Callers only see the BookIterator interface (hasNext()/next()). BookShelf hands out two different concrete iterators: ForwardIterator walks every book in order, and DecadeIterator filters to only books published in a given decade, computing the next match lazily as advance() is called. Main exercises both iterators, then prints a line noting that java.util.Iterator/for-each work the same way under the hood.

How to run

javac iterator/*.java -d out/iterator
java -cp out/iterator iterator.Main

Requires Java 25.

Post Section ↔ File Mapping

Post Section File(s)
Custom Iterator Implementation — the Iterator interface BookIterator.java
Custom Iterator Implementation — the element type Book.java
Custom Iterator Implementation — the Aggregate (BookShelf, ForwardIterator, DecadeIterator) BookShelf.java
Custom Iterator Implementation — wiring it together Main.java

Note: the "How Java's For-Each Loop Uses Iterator" snippet (Iterable<Book> example) is illustrative only — it is not part of this repository's runnable example.

Article: https://ankurm.com/iterator-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/