Sub topic 6
Removing Elements Safely While Iterating
You often need to loop over a list and delete some items as you go. For example, you might remove every empty string or every expired order. This sounds simple, but the most obvious way to do it is wrong in Java. This chapter shows why it breaks and covers four safe ways to do it.
You already know how to loop with a for-each loop and an Iterator from the previous chapter. Here we focus on what happens when the collection changes during the loop.
The problem: changing a list inside a for-each loop
Here is the code most people write first. It tries to remove every one-letter word from a list.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class BrokenRemoveDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("a", "bb", "c", "dd"));
try {
for (String w : words) {
if (w.length() == 1) {
words.remove(w);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Caught: " + e);
}
System.out.println(words); // [bb, c, dd]
}
}The output is:
Caught: java.util.ConcurrentModificationException
[bb, c, dd]A ConcurrentModificationException is an error Java throws when a collection changes in a way the running loop did not expect. The word "concurrent" makes it sound like a threading problem. Here there is only one thread. The loop and the remove call simply step on each other.
Notice that the loop stopped early. The word "c" was never removed, because the error ended the loop before it got there.
Why it happens: the modification count
A for-each loop is a shortcut. Behind the scenes, Java creates an Iterator and calls hasNext() and next() for you.
An ArrayList keeps a hidden number called modCount (modification count). It goes up by one every time the list changes size, for example on add or remove. When the iterator is created, it copies that number. Each time you call next(), the iterator checks whether the list's modCount still matches its copy. If the numbers differ, someone changed the list behind the iterator's back, and it throws the exception.
This check is called fail-fast behavior. A fail-fast iterator stops with an error as soon as it notices a problem, instead of carrying on with wrong data.
A worse case: no error, but wrong results
You might think "at least Java warns me." It does not always. If you remove the second-to-last element, the loop can end quietly and skip the last one.
import java.util.ArrayList;
import java.util.List;
public class SilentSkipDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("aa", "b", "c"));
for (String w : words) {
if (w.length() == 1) {
words.remove(w);
}
}
System.out.println(words); // [aa, c]
}
}No exception is thrown, yet "c" is still in the list. After "b" is removed, the list has 2 elements and the iterator's position is also 2. So hasNext() returns false, and the loop never looks at "c".
The same trap with an index loop
A classic for loop with an index does not throw this exception, because it uses no iterator. It has a different bug. When you remove an item, every later item shifts one place to the left, and the loop jumps over the item that moved into the gap.
import java.util.ArrayList;
import java.util.List;
public class IndexLoopDemo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(2, 4, 5, 6));
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) % 2 == 0) {
nums.remove(i); // int argument: removes by index
}
}
System.out.println(nums); // [4, 5] (4 was skipped)
List<Integer> fixed = new ArrayList<>(List.of(2, 4, 5, 6));
for (int i = fixed.size() - 1; i >= 0; i--) {
if (fixed.get(i) % 2 == 0) {
fixed.remove(i);
}
}
System.out.println(fixed); // [5]
}
}In the first loop, removing 2 at index 0 moves 4 into index 0. Then i becomes 1, so 4 is never checked.
The second loop walks backward, from the last index down to 0. Removing an item only shifts the items after it, and the loop has already checked those. So nothing is skipped.
Recall from the autoboxing chapter that remove(i) with an int removes by index. That is exactly what we want here.
Safe way 1: Iterator.remove
If you use an Iterator directly, you can call its own remove() method. It deletes the element that next() returned most recently. Because the iterator makes the change itself, it updates its saved count and stays in step with the list.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorRemoveDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ana", "Ben", "Bo", "Cara"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
if (name.startsWith("B")) {
it.remove();
}
}
System.out.println(names); // [Ana, Cara]
Iterator<String> it2 = names.iterator();
try {
it2.remove(); // no next() call yet
} catch (IllegalStateException e) {
System.out.println("Call next() before remove()");
}
}
}There are two rules for Iterator.remove():
- Call
next()first.remove()deletes the last elementnext()gave you. - Call
remove()at most once pernext(). Breaking either rule throwsIllegalStateException, which is an error meaning "this method was called at the wrong time."
Safe way 2: removeIf
Since Java 8, every collection has a removeIf method. You pass it a predicate, which is a small function that returns true or false for each element. Every element that gets true is removed. removeIf itself returns true if it removed anything.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RemoveIfDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "", "kiwi", "", "fig"));
boolean changed = words.removeIf(String::isEmpty);
System.out.println(changed); // true
System.out.println(words); // [apple, kiwi, fig]
boolean again = words.removeIf(String::isEmpty);
System.out.println(again); // false, nothing left to remove
Map<String, Integer> stock = new HashMap<>();
stock.put("pears", 0);
stock.put("apples", 10);
stock.values().removeIf(count -> count == 0);
System.out.println(stock.containsKey("pears")); // false
System.out.println(stock.containsKey("apples")); // true
}
}The stock part gives you a first look at maps, which a later chapter covers. A map's values(), keySet(), and entrySet() views also support removeIf. Removing through a view removes the matching entries from the map itself.
Safe way 3: collect first, then remove
Sometimes the decision about what to delete takes several steps. In that case, loop once to collect the items to delete into a second list. Then remove them all after the loop ends.
import java.util.ArrayList;
import java.util.List;
public class CollectThenRemoveDemo {
public static void main(String[] args) {
List<String> orders = new ArrayList<>(List.of("A1", "X9", "B2", "X3"));
List<String> toRemove = new ArrayList<>();
for (String order : orders) {
if (order.startsWith("X")) {
toRemove.add(order);
}
}
orders.removeAll(toRemove);
System.out.println(orders); // [A1, B2]
}
}This works because the loop only reads orders. All changes happen after the loop is finished.
Choosing an approach
| Approach | Safe? | Good for |
|---|---|---|
| `list.remove` inside for-each | No | Never use it |
| Forward index loop with `remove(i)` | No, skips items | Never use it for removal |
| Backward index loop | Yes | When you need the index |
| `Iterator.remove()` | Yes | Complex logic, one pass |
| `removeIf` | Yes | Most cases, simple conditions |
| Collect, then `removeAll` | Yes | Decisions that need the whole list |
Edge cases to remember
- Unmodifiable lists. A list from
List.of(...)cannot change at all. CallingremoveIforIterator.remove()on it throwsUnsupportedOperationException. Copy it first withnew ArrayList<>(List.of(...)), as the examples in this chapter do. - Adding during a loop. Calling
list.addinside a for-each loop causes the same exception. If you need to insert while walking a list, aListIterator(fromlist.listIterator()) has its ownaddmethod that is safe. - Sets and maps.
HashSetandHashMapiterators are fail-fast too. The same safe approaches work on them:Iterator.remove(),removeIf, and removing through a map's views.
Exercise
This code should remove every negative number, but it prints [-2, 3] instead of [3]. Explain why, and rewrite it in one line so it works. Code: List<Integer> nums = new ArrayList<>(List.of(-1, -2, 3)); for (int i = 0; i < nums.size(); i++) { if (nums.get(i) < 0) nums.remove(i); }
Show answer
Removing -1 at index 0 shifts -2 into index 0. The loop then moves to index 1, which holds 3, so -2 is never checked. The fix is nums.removeIf(n -> n < 0); which checks every element and prints [3]. A backward index loop would also work.
Exercise
What happens when this code runs, and why? Code: List<String> list = new ArrayList<>(List.of("x", "y")); Iterator<String> it = list.iterator(); it.next(); it.remove(); it.remove();
Show answer
The first it.remove() deletes "x". The second call throws IllegalStateException, because remove() may be called only once for each call to next(). To remove "y" as well, call it.next() again before the second remove().
Exercise
A for-each loop over ["aa", "b", "c"] calls list.remove(w) whenever w has length 1. It throws no exception. Is the code correct? What is the final list?
Show answer
No, the code is wrong. The final list is [aa, c]. After "b" is removed, the list size (2) equals the iterator's position (2), so hasNext() returns false and "c" is never checked. The missing exception does not mean the code is safe. Use removeIf or Iterator.remove instead.