Iterators

Paul Ngugi - Jul 9 - - Dev Community

Each collection is Iterable. You can obtain its Iterator object to traverse all the elements in the collection. Iterator is a classic design pattern for walking through a data structure without having to expose the details of how data is stored in the data structure.

The Collection interface extends the Iterable interface. The Iterable interface defines the iterator method, which returns an iterator. The Iterator interface provides a uniform way for traversing elements in various types of collections. The iterator() method in the Iterable interface returns an instance of Iterator, as shown in Figure below, which provides sequential access to the elements in the collection using the next() method. You can also use the hasNext() method to check whether there are more elements in the iterator, and the remove() method to remove the last element returned by the iterator.

Image description

The code below gives an example that uses the iterator to traverse all the elements in an array list.

Image description

The program creates a concrete collection object using ArrayList (line 7) and adds four strings into the list (lines 8–11). The program then obtains an iterator for the collection (line 13) and uses the iterator to traverse all the strings in the list and displays the strings in uppercase (lines 14–16).

You can simplify the code in lines 13–16 using a foreach loop without using an iterator, as follows:

for (String element: collection)
System.out.print(element.toUpperCase() + " ");

This loop is read as “for each element in the collection, do the following.” The foreach loop can be used for arrays as well as any instance of Iterable.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .