Using Iterators

An iterator is an object that “provides a means of enumerating (selecting one by one) the contents of a collection”.  That is, an iterator allows one to loop through the elements of the collection so as to be able to perform some computation with each element.

A class that provides an iterator usually implements the Iterable<T> interface which requires it to implement a method named iterator that returns and Iterator<T> object.

Iterator<T> iterator();

The Iterator<T> object returned by iterator is used to enumerate the contents of the collection, one by one.

Most of the concrete collection classes in the Java Collection Framework implement the Iterator<T> interface.

The Iterator Interface

The Iterator interface has two main methods: hasNext() and next().

boolean hasNext();
E next();

The first method, hasNext() returns true if there are more elements to iterate over.  The method next() returns the next element in the iteration.  These methods are often used with a while-loop to iterate over all of the elements in the collections as shown below.

Iterator<String> it = list.iterator(); 
while(it.hasNext()) {
    System.out.println(it.next());
}

In the example above, we assume we have created a List (of lets say Strings) which is referenced by the variable list. To iterate over the String elements in the list, we first obtain an Iterator object by calling the list object’s iterator method.  We then use the iterator object’s hasNext method to determine whether or not to execute the block of code in the while-loop.  If hasNext returns true, we call the iterator’s next method to get the next element which we can then do something with (like print to the screen).

For-each Loops

A for-each loop iterates over the collection and assigns to a local variable (elm in the example below) the value of each element in the collection, one by one.  If you do not need to replace or remove the elements in the collection then the for-each loop is an easier way to implicitly utilize the class’ iterator to iterate over the elements in the collection.

for (String elm : list)
    System.out.println(elm);

Remove

The Iterator interface also has a method named remove.  Remove has a default implementation, so when implementing the interface you need not provide a remove method.  If the method is not overridden it will throw an UnsupportedOperationException.  If it is supported it should remove the last element returned by the iterator’s next method.

String pattern = ...
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    String elm = it.next();
    if (elm.equals(pattern))
        it.remove();  // should remove object currently in elm
}

© 2017 – 2019, Eric. All rights reserved.