CodeBlanks Logo Icon CodeBlanks

remove

Learn safe removal with Iterator.remove.

The iterator.remove() method

To remove an element during traversal use iterator.remove(). This method deletes the element most recently returned by next(). Calling remove on the same Iterator without a prior next throws IllegalStateException.

Modifying a list inside a for-each loop is forbidden; it throws ConcurrentModificationException. For conditional removal, the Iterator's remove method is the safe path.

The conditional removal pattern

The classic pattern for conditional removal is while (it.hasNext()) { String s = it.next(); if (condition) it.remove(); }. After each removal the Iterator cursor stays in place; the next next call returns the new element.

This pattern is ideal for cleaning a list of elements that match a condition. For example s.length() > 5 drops long names, s.isEmpty() drops empty strings. remove can be called at most once per next.

Practice Remove long names with an Iterator

Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alexander", "Alex". Get an Iterator with Iterator<String> it = names.iterator();. In a while (it.hasNext()) loop call String s = it.next();; if s.length() > 5 call it.remove();. After the loop print the remaining count with System.out.println(names.size());.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add 3 names, Iterator removes names longer than 5, print count

    }
}

Sample solution

Main.java
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alexander");
        names.add("Alex");
        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.length() > 5) it.remove();
        }
        System.out.println(names.size());
    }
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the remove call

Question
String s = it.next();
if (s.isEmpty()) {
    it.____();
}
Answer
String s = it.next();
if (s.isEmpty()) {
    it.remove();
}

Explanation: The remove method deletes the last read element.

2 When does it.remove() throw IllegalStateException?

  • Before next is called Correct answer
  • When hasNext returns false
  • When remove is called twice
  • When the list is empty

Explanation: Calling remove before next throws IllegalStateException.

3 Match the remove behaviors

Term Meaning
remove() Deletes last read
IllegalStateException remove without next
ConcurrentModificationException Removal in for-each
next() Required before remove

All lessons in Intermediate