01 / 21

Using Iterator
in Java

Learn how to traverse and safely remove elements from collections using Java's Iterator interface.

Java Programming

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

hasNext()
Returns true if there are more elements to visit. Does not advance the cursor.
next()
Returns the next element and advances the cursor forward by one position.
remove()
Removes the last element returned by next(). The only safe way to delete during traversal.

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

ArrayList<String> "A" "B" "C" "D" "E" 1. .iterator() Cursor before "A" 2. hasNext() returns true 3. next() returns "A", moves cursor advance 4. remove() removes "A" safely while ( it.hasNext() ) String s = it.next(); if (condition) it.remove(); Repeat until hasNext() returns false

The Iterator Pattern

Java
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

1
Obtain the Iterator: call collection.iterator() to get a fresh cursor positioned before the first element.
2
Check with hasNext(): use a while loop that continues as long as hasNext() returns true.
3
Retrieve with next(): call next() to get the current element and advance the cursor.
4
Remove if needed: call it.remove() to delete the element just returned by next(). Never call remove() twice without next() in between.

Example 1: Print All Elements

Java
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

Java
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

✕ Wrong
for (String s : list) {
  if (s.equals("X"))
    list.remove(s);
}
// ConcurrentModification
// Exception!
✓ Correct
Iterator<String> it
  = list.iterator();
while (it.hasNext()) {
  if (it.next().equals("X"))
    it.remove();
}
// Works perfectly!

Visualizing Safe Removal

BEFORE REMOVE 1 2 3 4 cursor last returned it.remove() AFTER REMOVE 1 3 4 cursor Element "2" is removed. Cursor adjusts automatically. Next call to next() will return "3" as expected.

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.

Java
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.

hasPrevious()
Move backward through the list, not just forward.
set(E e)
Replace the last element returned by next() or previous().
add(E e)
Insert an element at the current cursor position.

Common Mistakes

✕ Calling remove() twice
You must call next() between each remove(). Two removes without next() throws IllegalStateException.
✕ Modifying collection directly
Calling list.remove() or list.add() during iteration causes ConcurrentModificationException.
✕ Calling next() past the end
Calling next() when hasNext() is false throws NoSuchElementException. Always check first.

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

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?