Behavioral Design Pattern · Java

Iterator Design Pattern in Java

Traverse a collection without exposing how the collection stores its data.

What is Iterator?

Iterator gives clients a consistent next/hasNext API. Java’s Iterable and Iterator interfaces provide this pattern in the standard library.

Beginner-friendly Java example

Focus on the roles in the example first. The pattern becomes easier when you can identify the sender, receiver, context, state, or strategy involved.

List<String> orders = List.of("A-101", "A-102", "A-103");

Iterator<String> iterator = orders.iterator();
while (iterator.hasNext()) {
    String orderId = iterator.next();
    System.out.println("Processing " + orderId);
}

for (String orderId : orders) {
    System.out.println(orderId);
}

Benefits and trade-offs

Benefits
  • Keeps responsibilities focused.
  • Reduces conditional and tightly coupled code.
  • Makes behavior easier to extend and test.
Trade-offs
  • Can introduce extra objects and interfaces.
  • Too many small classes can make simple logic harder to follow.

Real-time use cases

  • Walking collections and trees
  • Pagination results
  • Streaming records
  • Custom data structures
Key takeawayTraverse a collection without exposing how the collection stores its data. Use it when behavior or communication is changing faster than the objects themselves.