Java Iterator

The Java Iterator Interface

An Iterator is an object that can be used to loop through collections, like ArrayList, HashSet, etc. It is an interface in the Java Collections Framework.

Getting an iterator is easy. You can call the iterator() method on any collection object.


Why Use an Iterator?

While you can loop through a collection with a for-each loop, an Iterator gives you one crucial ability: safely removing elements from a collection while iterating over it.

Trying to remove an element from a collection using a for-each loop will cause a ConcurrentModificationException. The Iterator's remove() method is the only safe way to modify a collection during iteration.


Iterator Methods

The Iterator interface has three main methods:

Method Description
boolean hasNext() Returns true if the iteration has more elements.
E next() Returns the next element in the iteration.
void remove() Removes from the underlying collection the last element returned by this iterator. This method can be called only once per call to next().

Looping Through a Collection

Here is an example of using an Iterator to loop through an ArrayList.

Using an Iterator

import java.util.ArrayList;
import java.util.Iterator;

public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); // Get the iterator Iterator<String> it = cars.iterator(); // Loop through the collection while(it.hasNext()) { System.out.println(it.next()); } } }


Removing Items from a Collection

The following example shows how to safely remove items from a collection during a loop. Let's remove all cars with the letter 'o'.

Safely Removing with an Iterator

import java.util.ArrayList;
import java.util.Iterator;

public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); Iterator<String> it = cars.iterator(); while(it.hasNext()) { String car = it.next(); if(car.contains("o")) { it.remove(); // Safe removal } } System.out.println(cars); } }

If you tried to do cars.remove(car) inside a for-each loop, the program would crash with an exception. The Iterator is the correct tool for this job.