The Iterator is one of the simplest and most frequently used of the
design patterns. The Iterator pattern allows you to move through a list or
collection of data using a standard interface without having to know the
details of the internal representations of that data. In addition you can also
define special iterators that perform some special processing and return only
specified elements of the data collection.
In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.
For example, a tree, linked list, hash table, and an array all need to be iterated with the methods search, sort, and next. Rather than having 12 different methods to manage (one implementation for each of the previous three methods in each structure), using the iterator pattern yields just seven: one for each class using the iterator to obtain the iterator and one for each of the three methods. Therefore, to run the search method on the array, you would call array.search(), which hides the call to array.iterator.search().
Structure
Motivation
The Iterator is useful because it provides a defined way to move
through a set of data elements without exposing how it does it. Since the
Iterator is an interface, you can implement it in any way that is convenient for
the data you are returning.
The Iterator of choice in Java is Java’s built-in Enumeration type.
Filtered Iterators
While having a clearly defined method of moving through a
collection is helpful, you can also define filtered Enumerations that perform
some computation on the data before returning it. For example, you could
return the data ordered in some particular way, or only those objects that
match a particular criterion. Then, rather than have a lot of very similar
interfaces for these filtered enumerations, you simply provide a method
which returns each type of enumeration, with each one of these enumerations
having the same methods.