behavioral
Iterator
Provide a way to access elements of an aggregate sequentially while hiding the underlying representation.
Problem
A collection needs to be traversed without exposing how it is stored internally.
Integration notes
Iterator is useful for pagination, custom collections, ordered traversal, and any case where clients should not know the internal data structure.
Tradeoffs
- Can add extra classes and abstraction for simple collections
- May be unnecessary when built-in language iteration is already enough
Languages
typescript, java, python, angular, react, react-native, csharp, dotnet
Platforms
Web, Backend, Mobile, UI kits, Cross-platform systems
Variants
Scenarios
Playlist iterator
A playlist exposes songs one at a time through a custom iterator.
Language examples
Core languages
Frameworks and libraries
Playlist iteratortypescript
The playlist iterator exposes songs one by one while hiding how the playlist stores its internal list.
TypeScript
interface Iterator<T> {
next(): T | null;
hasNext(): boolean;
}
class PlaylistIterator implements Iterator<string> {
private index = 0;
constructor(private songs: string[]) {}
next(): string | null {
if (!this.hasNext()) {
return null;
}
return this.songs[this.index++];
}
hasNext(): boolean {
return this.index < this.songs.length;
}
}
class Playlist {
constructor(private songs: string[]) {}
createIterator(): Iterator<string> {
return new PlaylistIterator(this.songs);
}
}
const playlist = new Playlist(["Intro", "First Song", "Second Song"]);
const iterator = playlist.createIterator();
while (iterator.hasNext()) {
console.log(iterator.next());
}Real-world examples
- Music apps: Music players often need next, previous, shuffle, and custom traversal behavior.
- Pagination: APIs commonly expose data in pages while the client iterates through results sequentially.
- Tree walking: File systems, DOM trees, and hierarchical categories often require structured traversal.