Using the Iterator Interface

Contact Us or call 1-877-932-8228
Using the Iterator Interface

Using the Iterator Interface

Iterators provide a standard way to loop through all items in a collection, regardless of the type of collection. Note that:

  • All collection classes implement an iterator() method that returns the object's iterator (declared as Iterator iterator()).
  • This method is specified by the Iterable interface, which is the base interface for Collection.
  • For maps, the collection itself is not Iterable, but the set of keys and the set of entries are.
  • You can use a for-each loop for any Iterable object.

Without an iterator, you could still use an indexed loop to walk through a list using the size() method to find the upper limit, and the get(int index) method to retrieve an item, but other types of collections may not have the concept of an index, so an iterator is a better choice.

There are two key methods supplied by an iterator:

  1. boolean hasNext(), which returns true until there are no more elements.
  2. Object next(), which retrieves the next element and also moves the iterator's internal pointer to it.

Some collections allow you to remove an element through the iterator. The remove method is marked in the docs as optional by the definition of interfaces it has to be present, but the optional status indicates that it may be implemented to merely throw an UnsupportedOperationException.

In any case, if the collection is modified from a route other than via the iterator (perhaps by using remove(int index), or even just using the add method), a ConcurrentModificationException is thrown.

The Enumeration class is an older approach to this concept; it has methods hasMoreElements() and nextElement().

Code Sample:

import java.util.*;

public class CollectionsTest {
  public static void main(String[] args) {
    List l = new ArrayList();
    Map m = new TreeMap();
    Set s = new TreeSet();
    l.add(new Integer(1));
    l.add(new Integer(4));
    l.add(new Integer(3));
    l.add(new Integer(2));
    l.add(new Integer(3));
    m.put(new Integer(1), "A");
    m.put(new Integer(4), "B");
    m.put(new Integer(3), "C");
    m.put(new Integer(2), "D");
    m.put(new Integer(3), "E");
    System.out.println("Adding to Set");
    System.out.println("Adding 1: " + s.add(new Integer(1)));
    System.out.println("Adding 4: " + s.add(new Integer(4)));
    System.out.println("Adding 3: " + s.add(new Integer(3)));
    System.out.println("Adding 2: " + s.add(new Integer(2)));
    System.out.println("Adding 3: " + s.add(new Integer(3)));
    Iterator i = l.iterator();
    while (i.hasNext()) System.out.println(;
    System.out.println("Map using keys");
    i = m.keySet().iterator();
    while (i.hasNext()) System.out.println(m.get(;
    System.out.println("Map using entries");
    i = m.entrySet().iterator();
    while (i.hasNext()) System.out.println(;
    i = s.iterator();
    while (i.hasNext()) System.out.println(;

This program demonstrates the three types of collections. As is commonly done, the variables are typed as the most basic interfaces (List, Set, and Map).

We attempt to add the same sequence of values to each: 1, 4, 3, 2, and 3; then:

  • They are deliberately out of sequence and contain a duplicate.
  • For the Map, the numbers are the keys, and single-letter strings are used for the associated values.

In the output, first note the true and false values resulting from attempting to add the values to the Set. Also note in the Map listing, which value associated with the key 3 is retained.

An iterator is then obtained for each and the series printed out (for the Map, we try two different approaches: iterating through the keys and retrieving the associated entries, and iterating directly through the set of entries).

Note the order of the values for each, and also which of the duplicates was kept or not. Note also that:

  • Tthe List object stores all the objects and iterates through them in order of addition.
  • The Map object stores by key; since a TreeMap is used, its iterator returns the elements sorted in order by the keys.
  • Since one key is duplicated, the later of the two values stored under that key is kept.
  • The Set object rejects the duplicate, so the first item entered is kept (although in this case it would be hard to tell from the iterator listing alone which one was actually stored).