Using Iterator
in Java
Learn how to traverse and safely remove elements from collections using Java's Iterator interface.
What Is an Iterator?
An Iterator is an object that lets you step through the elements of a collection one at a time, without exposing the collection's internal structure. It lives in java.util.Iterator.
The Three Core Methods
Why Not Just Use a For Loop?
An enhanced for-each loop works great for reading elements. But if you try to remove an element from a collection while iterating with a for-each loop, Java throws a ConcurrentModificationException.
Iterator Lifecycle
The Iterator Pattern
Iterator<String> it = list.iterator(); while (it.hasNext()) { String element = it.next(); // process element if (shouldRemove(element)) { it.remove(); // safe removal } }
Iterator vs For-Each
| Iterator | For-Each Loop | |
|---|---|---|
| Syntax | Verbose (3 method calls) | Concise, clean |
| Read elements | ✓ Yes | ✓ Yes |
| Remove during loop | ✓ Safe with remove() | ✕ Throws exception |
| Access index | ✕ No built-in index | ✕ No built-in index |
| Works with | Any Iterable | Any Iterable + arrays |
How to Apply Iterator
Example 1: Print All Elements
List<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> it = fruits.iterator(); while (it.hasNext()) { System.out.println(it.next()); }
Example 2: Remove Even Numbers
List<Integer> nums = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6)); Iterator<Integer> it = nums.iterator(); while (it.hasNext()) { int n = it.next(); if (n % 2 == 0) { it.remove(); // safe! } } // nums is now [1, 3, 5]
Example 3: The Danger Zone
if (s.equals("X"))
list.remove(s);
}
// ConcurrentModification
// Exception!
= list.iterator();
while (it.hasNext()) {
if (it.next().equals("X"))
it.remove();
}
// Works perfectly!
Visualizing Safe Removal
Iterator with Set
Iterator isn't limited to Lists. It works with any Collection: Set, Queue, Deque. For a HashSet, the iteration order is not guaranteed, but the pattern is identical.
Set<String> names = new HashSet<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); Iterator<String> it = names.iterator(); while (it.hasNext()) { String name = it.next(); if (name.startsWith("B")) { it.remove(); } } // "Bob" removed from the set
ListIterator: Extra Powers
Lists offer a more powerful variant called ListIterator. It extends Iterator with bidirectional movement and modification abilities.
Common Mistakes
Summary Table
| Scenario | Use This | Why |
|---|---|---|
| Read all elements | For-each loop | Cleanest syntax |
| Remove during traversal | Iterator | Only safe approach |
| Replace / insert during traversal | ListIterator | Has set() and add() |
| Need index | Traditional for loop | Direct index access |
| Filter + remove (Java 8+) | removeIf() | One-liner shortcut |
Question 1 of 5
Which method of Iterator returns the next element and advances the cursor?
Question 2 of 5
What exception is thrown if you call list.remove() inside a for-each loop?
Question 3 of 5
List<String> items = new ArrayList<>(
Arrays.asList("A", "B", "C", "D"));
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("B") || s.equals("D")) {
it.remove();
}
}
System.out.println(items);
What does the code above print?
Question 4 of 5
What happens if you call it.remove() twice in a row without calling next() between them?
Question 5 of 5
Which of the following is NOT a method provided by the standard Iterator interface?