Java - Iterator
Iterator
import java.util.*;
List xs = new ArrayList<>(List.of(1,2,3));
for (Iterator it = xs.iterator(); it.hasNext();) {
int v = it.next();
if (v % 2 == 0) it.remove(); // safe removal
}
Use the iterator’s remove method to avoid ConcurrentModificationException.
Try it
- Remove even numbers from a list using an explicit iterator safely.
- Compare with
removeIf
using a predicate.