Iterator
Traverse any collection — list, tree, graph, custom data structure — through a consistent interface without exposing how it's actually stored.
Intent & Description
🎯 Intent
Give clients a uniform way to step through any collection regardless of its underlying storage structure.
📋 Context
You have multiple collection types — arrays, linked lists, trees, database result sets — and client code that needs to traverse them all. Exposing internal structure forces clients to know too much and breaks when you change implementations.
💡 Solution
Define an Iterator with next() and hasNext(). Each collection returns its own Iterator implementation. Client code uses the Iterator interface and never sees how the collection stores its data. Multiple iterators can traverse the same collection independently.
Real-world Use Case
Source
📌 TL;DR
Uniform traversal interface for any collection type. Client code doesn’t care if it’s an array, tree, or database cursor — it just calls next(). Overkill for simple lists.
Advantages
- Client code is agnostic to how the collection stores its data.
- Multiple iterators can traverse the same collection independently and simultaneously.
Disadvantages
- Pure overhead for simple arrays or collections that are already easily traversable.
class AlphabeticalIterator {
constructor(collection) {
this.collection = collection;
this.position = 0;
}
next() {
const item = this.collection.getItems()[this.position];
this.position += 1;
return item;
}
hasNext() {
return this.position < this.collection.getCount();
}
}