What is the purpose of the Iterator pattern?
The purpose of the Iterator pattern is to provide a single way to sequentially traverse the elements of a collection, without exposing its internal structure.
1. The Core Idea
Instead of the client working directly with arrays, lists, or trees, the iterator takes over the logic of moving from one element to the next.
The client doesn't need to know:
- how the collection is structured,
- how it stores its data,
- what the traversal logic is (in order, in depth, by filter, and so on).
It simply uses a single interface:
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object item = iterator.next();
}2. Why It's Needed
- To separate the traversal algorithm from the collection's structure.
- To unify access to elements of different containers (lists, trees, hash maps).
- To support multiple traversal methods without duplicating logic.
3. Advantages
- Encapsulation of the collection's internal structure.
- The ability to create different types of iterators (forward, reverse, filtering).
- Simplified client code, traversal always looks the same.
4. Example (Java)
List<String> list = List.of("A", "B", "C");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}The client doesn't know that an ArrayList is backed by an array internally;
it just fetches elements sequentially.
Conclusion
The Iterator pattern makes collections convenient and universal to use, letting you traverse them without knowing their internal structure and providing a single navigation interface over the elements.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.