🔍 Iterator Design Pattern – In-Depth Guide
1. What is the Iterator Pattern?
The Iterator Design Pattern is a behavioral design pattern that provides a way to access elements of a collection (list, array, map, tree, etc.) sequentially without exposing the internal representation.
💡 Core Idea:
“You don’t need to know how a collection is built, you just need a standard way to loop through it.”
2. Example 🏡
Imagine a TV remote with channel up/down buttons:
3. When to Use Iterator Pattern?
✅ To traverse different kinds of collections in a uniform way. ✅ To provide sequential access without exposing internal data structures. ✅ When you want to decouple iteration logic from the collection itself.
4. UML Structure 🔗
5. Simple Example (Custom Collection)
// Iterator Interface
interface Iterator<T> {
boolean hasNext();
T next();
}
// Aggregate Interface
interface Container<T> {
Iterator<T> getIterator();
}
// Concrete Aggregate
class NameRepository implements Container<String> {
private String[] names = {"Arjun", "Suraj", "Neha", "Rahul"};
public Iterator<String> getIterator() {
return new NameIterator();
}
// Concrete Iterator
private class NameIterator implements Iterator<String> {
int index = 0;
public boolean hasNext() {
return index < names.length;
}
public String next() {
return hasNext() ? names[index++] : null;
}
}
}
// Client
public class IteratorDemo {
public static void main(String[] args) {
NameRepository repo = new NameRepository();
Iterator<String> iterator = repo.getIterator();
while (iterator.hasNext()) {
System.out.println("Name: " + iterator.next());
}
}
}
Output:
Name: Arjun
Name: Suraj
Name: Neha
Name: Rahul
Recommended by LinkedIn
6. Real-World / Production Use Cases 🚀
a) Collections Framework (Java, C#, Python, etc.)
b) Tree / Graph Traversals
c) Streaming Data / APIs
d) Database Cursors
7. Advantages ✅
8. Limitations ⚠️
9. Real Production Analogy 🌍
Think of Netflix’s “Next Episode” button:
✅ Conclusion: The Iterator Pattern is everywhere — in Java’s Iterable, Python’s __iter__, C#’s IEnumerator, even database cursors. It abstracts traversal so developers can focus on logic, not structure.