Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
Iterator pattern is widely used in Java Collection Framework where
Iterator interface provides methods for traversing through a collection.1
For example, consider the following code snippet:
The enhanced for loop is a syntax sugar for:
TreeSet.iterator() returns an iterator over the elements in ascending order. Iterator pattern is not only about traversing through a collection, but we can also provide different kind of iterators based on our requirements. For instance, if you were interested in getting the
TreeSet elements in descending order, you could use
Typically, the iterator algorithm is implemented in a separate classes.2 This separation is following the Single Responsibility principle.
The use of
Iterable (as a separate interface with just one method) is in line with the Interface Segregation Principle. Moreover, the use of
Iterator interface is in accordance to the Open/Closed principle; you can implement new types of iterators and pass them to existing code without breaking anything.
When to use this pattern?
Use the Iterator pattern when your collection has a complex data structure under the hood, but you want to hide its complexity from clients (either for convenience or security reasons).
Iterator pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods.