Syntax
Iterator<Type> it = collection.iterator();Examples
Basic Iterator Usage
Manually stepping through a collection with hasNext() and next().
import java.util.ArrayList;
import java.util.Iterator;
ArrayList<String> names = new ArrayList<>();
names.add("Fola");
names.add("Zain");
names.add("Jamal");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
System.out.println(name);
}Safely Removing Elements While Iterating
The key advantage of Iterator over a for-each loop: safe removal during traversal.
import java.util.ArrayList;
import java.util.Iterator;
ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 10; i++) numbers.add(i);
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int num = it.next();
if (num % 2 == 0) {
it.remove(); // safe removal - use it.remove(), not numbers.remove()
}
}
System.out.println(numbers); // [1, 3, 5, 7, 9]Why a for-each Loop Cannot Safely Remove
Directly modifying a collection during a for-each loop throws an exception.
import java.util.ArrayList;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
try {
for (int num : numbers) {
if (num == 2) {
numbers.remove(Integer.valueOf(2)); // modifying during for-each
}
}
} catch (java.util.ConcurrentModificationException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}Best practices
- Use it.remove() through an Iterator when you need to delete elements while looping - never call collection.remove() directly inside a for-each loop
- Use a for-each loop for simple read-only iteration - it is more concise than manually managing an Iterator
- Use a ListIterator (available on List) instead of a plain Iterator when you also need to traverse backward or modify elements in place
- Remember an Iterator becomes invalid ("fails fast") if the underlying collection is structurally modified by anything other than the iterator itself
At a glance
- Purpose
- General-purpose application development
- File extension
- .java
- Runs in
- Java Virtual Machine
- Usually used with
- JDK and Java libraries
Specifications & further reading
Related Java documentation
ArrayList
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashMap
HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).HashSet
HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashMap
HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).HashSet
HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.