Iterator#

The Iterator pattern is a behavioral design pattern that allows you to traverse elements of a collection (like a list or a set) without exposing the underlying representation. It provides a way to access the elements of an aggregate object sequentially without exposing its underlying structure.

In simpler terms, it allows you to loop through a collection of objects in a standard way without needing to know the details of how the collection is implemented.

Common use cases#

  1. Collections: Traversing elements in collections like lists, sets, or maps without exposing their internal structure.

  2. Tree Structures: Navigating through tree structures, such as DOM trees in web development.

  3. Custom Data Structures: Iterating over custom data structures where a standard iteration mechanism is not available.

  4. File Systems: Iterating over files and directories in a file system.

  5. Database Results: Traversing through rows in a database result set.

  6. Aggregated Data: Iterating over aggregated data from multiple sources.

  7. Streaming Data: Processing elements in a stream of data, such as log files or network packets.

UML Diagram#

+-------------------+      +-------------------+
|   Aggregate       |      |   Iterator        |
+-------------------+      +-------------------+
| +createIterator() |<>----| +next()           |
+-------------------+      | +hasNext()        |
                           +-------------------+
                                  ^
                                  |
                                  |
                           +-------------------+
                           | ConcreteIterator  |
                           +-------------------+
                           | -currentPosition  |
                           +-------------------+
                           | +next()           |
                           | +hasNext()        |
                           +-------------------+
                                  ^
                                  |
                                  |
                           +-------------------+
                           | ConcreteAggregate |
                           +-------------------+
                           | -items            |
                           +-------------------+
                           | +createIterator() |
                           +-------------------+
--- Java Example ---
--- Python Example ---