Tech and Media Labs
This site uses cookies to improve the user experience.


Java Iterator

Jakob Jenkov
Last update: 2018-09-22

The Java Iterator interface represents an object capable of iterating through a collection of Java objects, one object at a time. The Iterator interface is one of the oldest mechanisms in Java for iterating collections of objects (although not the oldest - Enumerator predated Iterator).

Obtaining an Iterator

Most often that is how you will interact with an Iterator by obtaining it from some Java object that contains multiple nested objects. For instance, you can obtain an Iterator from many of the Java Collection data structures, e.g. a List, Set, Map, Queue, Deque or Map.

Here is an example of obtaining a Java Iterator from a List instance:

List list = new ArrayList();

list.add("123");
list.add("456");
list.add("789");

Iterator iterator = list.iterator();

Iterating an Iterator

You iterate the objects in an Iterator using a while loop. Here is an example of iterating the elements of a Java Iterator using a while loop:

Iterator iterator = list.iterator();

while(iterator.hasNext()) {
    Object nextObject = iterator.next();

}

There are two methods to pay attention to in the above Java example. The first method is the Iterator hasNext() method which returns true if the Iterator contains more elements. In other words, if the Iterator has a next element.

The second method to pay attention to is the next() method. The next() method returns the next element of the collection the Iterator traverses.

Iteration Order

The order in which the elements contained in a Java Iterator are traversed depends on the object that supplies the Iterator. For instance, an iterator obtained from a List will iterate through the elements of that List in the same order the elements are stored internally in the List. An Iterator obtained from a Set, on the other hand, does not make any guarantees about the exact sequence the elements in the Set are iterated in.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC