Behavioral Design Pattern

Iterator Design Pattern in Java

Traverse a collection sequentially without exposing its internal representation.

In this lesson: Iterator provides a standard way to visit elements one at a time while keeping collection storage details private.

Overview

List topics = List.of("Java", "Spring Boot", "MySQL"); Iterator iterator = topics.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }

Implementation

class TopicCollection implements Iterable<String> { private final List<String> topics = new ArrayList<>(); public void add(String topic) { topics.add(topic); } public Iterator<String> iterator() { return topics.iterator(); } }
Use Iterator when callers need consistent traversal while the collection may change its internal representation.

When should you use it?

Use Iterator when clients need consistent traversal while the collection keeps control of its internal representation.

Next step: Continue with the Design Patterns course and explore the next pattern.