Java Iterators
An Iterator provides a standard way to traverse elements of a collection one at a time, using hasNext() to check for more elements and next() to retrieve the next one.
Iterators also allow safe removal of elements during iteration via remove(), which is not safe to do with a regular for-each loop (it throws ConcurrentModificationException).
Iterator<Type> it = collection.iterator();
while (it.hasNext()) {
Type item = it.next();
}Using Iterator
Call iterator() on a collection to get an Iterator, then loop with while (it.hasNext()) { it.next(); }.
Removing during iteration
Iterator.remove() safely removes the current element during iteration, avoiding ConcurrentModificationException that occurs when modifying a collection inside a for-each loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
int n = it.next();
if (n == 2) it.remove();
}
System.out.println(nums);
}
}[1, 3]The Iterator safely removes 2 from the list while iterating.
Key points
- hasNext() checks if more elements remain.
- next() retrieves and advances to the next element.
- Iterator.remove() safely removes elements during iteration.
- Modifying a collection directly in a for-each loop can throw ConcurrentModificationException.
