The iterator pattern allows for access and traversal of an aggregate object (list, map, etc.) without putting that overhead on the aggregate object. Iterator is responsible for keeping track of the current element, i.e., it knows which elements have been traversed already. The Iterator provides mechanism for accessing the list’s elements. An iterator object is responsible for keeping track of the current element, i.e., that is, it knows which elements have been traversed already.
In Java, the relationship between List and ListIterator interfaces can be depicted as follows:
- List – An ordered collection which gives precise control over where in the list each element is inserted. Elements can be accessed by their integer index (position in the list), and searched in the list
- ListIterator – Facilitates traversal of list in either direction, modification of list during traversal and obtain the current position in the list. A ListIterator does not have any current element. Its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().
Now let’s look at a concrete example of a list of numbers. The most common way to print numbers in a list is to use the good old “For Loop”.
for (int index=0; index < myNumbers.size(); index++)
for (int element:myNumbers)
Both the above-mentioned mechanisms work perfectly. However, with the introduction of lambdas, you can minimize the code size further. You can use internal iterators in the following manner:
You see how the code got reduced. It can be reduced even further:
The use of lambda functions while iterating list simplifies the code as the focus is on what to do to the element rather than indulging in the mechanisms of iterating the list.