CKTIS / Java
Iterator.remove() — removing an element during iteration
Iterator.remove() deletes the element most recently returned by next() from the underlying collection, if the iterator supports removal.
Version: Java SE 21
Syntax
default void remove()Iterator.remove() is a default method of java.util.Iterator<E>. Call it on the iterator, as in it.remove(). It takes no arguments and returns nothing (void). It removes the specific element that this iterator most recently returned from next(). You do not pass an index or a value.
After a successful next() call, you can remove the returned element only once. hasNext() only checks whether another element is available. An iterator that supports removal throws IllegalStateException if you call remove() before the first successful next() or call it again without another successful next().
Removal is optional. The default implementation makes no change and throws UnsupportedOperationException. An ArrayList iterator supports removal; an iterator from an unmodifiable list created with List.of() does not.
Do not replace it.remove() with a direct modification of the collection during iteration: the iterator's behavior is unspecified unless its implementation documents a concurrent modification policy. The Iterator contract also leaves the behavior of remove() after forEachRemaining() unspecified.
Examples
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 4, 5));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int number = it.next();
if (number % 2 == 0) {
it.remove();
}
}
System.out.println(numbers);
}
}Result
[1, 5]
`List.of()` supplies the initial values, and `ArrayList` makes a modifiable copy. The loop removes the adjacent even numbers `2` and `4`, each after a separate `next()` call, and prints `[1, 5]`.
Related lessons
- Java · Lesson 57 · Basic · Version: 2