Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Iterator remove: Safe Element Removal During Iteration

Learn how to use Java Iterator.remove() to safely delete elements from collections during iteration, avoid ConcurrentModificationException, and choose between removeIf and explicit iterators.

~4 min readJava
#Java Collections#Iterator#ConcurrentModificationException#removeIf
Illustration of Java Iterator.remove() removing an element from a collection during iteration.

When you need to remove elements from a Java collection while iterating over it, calling remove() on the collection itself is usually unsafe. For many standard collection types, such as ArrayList, this throws ConcurrentModificationException. The Iterator.remove() method exists specifically to solve this problem. It deletes the current element through the iterator instead of the collection, keeping the iterator's state consistent.

The Problem with Removing During Iteration

Java's fail-fast iterators are designed to detect structural modification of the underlying collection during iteration. If you call list.remove() inside an enhanced for loop, the collection's modification count changes without the iterator being notified. On the next next() call, the iterator compares the expected modification count with the actual one and throws ConcurrentModificationException.

java
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie")); for (String name : names) { if (name.equals("Bob")) { names.remove(name); // throws ConcurrentModificationException } }

The enhanced for loop hides the iterator, but the behavior is the same. If you need to remove the current element while keeping the iterator valid, use the iterator's own remove() method.

How Iterator.remove() Works

The Iterator interface defines remove() as an optional operation. Its contract is simple: it removes the last element returned by next() from the underlying collection. Calling remove() before next() or twice in a row throws IllegalStateException. The critical advantage is that the iterator updates its internal expected modification count to match the collection after removal, so iteration can continue without throwing.

java
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie")); Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.equals("Bob")) { iterator.remove(); } }

After this code runs, names contains ["Alice", "Charlie"]. The iterator remains valid and can continue processing the remaining elements.

Removing Elements with an Explicit Iterator

Using an explicit iterator gives you full control over the iteration and removal process. This is especially useful when you need to remove multiple elements or when the removal condition depends on state accumulated during iteration.

java
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6)); Iterator<Integer> iterator = numbers.iterator(); int sum = 0; while (iterator.hasNext()) { int value = iterator.next(); sum += value; if (sum > 6) { iterator.remove(); } }

Here, elements are removed based on a running total, something that is awkward to express with a simple condition. An explicit iterator is a viable fallback when removeIf is not available, but only if the collection's iterator supports remove(). Immutable collections and some specialized iterators may still reject remove() with UnsupportedOperationException.

Using removeIf for Simpler Cases

Java 8 introduced Collection.removeIf(Predicate), which removes all elements matching the predicate. Its default implementation works through an iterator, but collection types may override it with a more efficient bulk operation. This is the most concise and readable approach when the removal condition is a simple predicate.

java
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie")); names.removeIf(name -> name.equals("Bob"));

removeIf is defined on the Collection interface and works for any collection that supports element removal. You cannot call it on an array, and immutable collections reject it with UnsupportedOperationException. For arrays and immutable collections, build a new collection with the elements you want to keep; an explicit iterator is not a workaround when the collection itself does not support removal.

Handling ConcurrentModificationException

ConcurrentModificationException is not limited to enhanced for loops. It can also occur if the collection is structurally modified from another thread while you are iterating, although fail-fast detection is best-effort rather than guaranteed. The iterator's remove() method only protects you from modifications made through the same iterator. If another thread modifies the collection, you need external synchronization or a concurrent collection like CopyOnWriteArrayList.

java
List<String> list = new CopyOnWriteArrayList<>(List.of("A", "B", "C")); for (String s : list) { if (s.equals("B")) { list.remove(s); // safe with CopyOnWriteArrayList } }

CopyOnWriteArrayList creates a new underlying array on every modification, so its iterator never throws ConcurrentModificationException. However, this comes at a cost: each write is O(n), making it unsuitable for write-heavy workloads.

Performance and Memory Considerations

Removing elements during iteration has different costs depending on the collection type. For ArrayList, each removal shifts subsequent elements left, making a single removal O(n). Removing many elements one by one can therefore be O(n²). For LinkedList, removal of the current element is O(1) if you have the iterator, because the iterator holds a reference to the node. For bulk removal, removeIf is usually a good choice because some implementations remove all matches in one pass, but the exact performance depends on the JDK and collection implementation.

java
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5)); list.removeIf(n -> n % 2 == 0);

If you are removing many elements and want to avoid repeated element shifts, consider building a new list with the elements you want to keep. This uses extra memory but is often faster and simpler for large collections.

Choosing the Right Removal Approach

ApproachWhen to UseExample
Iterator.remove()When you need to remove the current element while iterating and you need the iterator's position to remain valid.Removing elements based on a running condition inside a loop.
Collection.removeIf()When the removal condition is a simple predicate and you are on Java 8 or later.Filtering a list based on a property of each element.
Stream + collectWhen you want to keep the original collection unchanged or need to transform the result.Creating a filtered copy of a collection.
CopyOnWriteArrayListWhen concurrent access is needed and reads are frequent or writes are rare.Read-heavy workloads with occasional modifications.

Use removeIf as your default for straightforward filtering. Fall back to an explicit iterator when you need to perform additional operations during iteration, such as accumulating state or removing elements based on a condition that changes as you go. For concurrent scenarios, choose a thread-safe collection rather than relying on Iterator.remove() alone.

Iterator.remove() remains a fundamental tool for safe in-place modification of collections. Understanding its contract and limitations helps you write robust code that avoids subtle runtime exceptions and performs well under varying workloads.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.