Senior
How to remove an element from a list during iteration over it?
sobes.tech AI
Answer from AI
It is dangerous to remove elements from a list during iteration directly, as this can lead to a ConcurrentModificationException or skipping elements. In Java, to safely remove elements while traversing a collection, use an iterator and its remove() method.
Example:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("b")) {
iterator.remove(); // safe removal
}
}
This approach guarantees correct removal without errors or skipping elements. If you use a for-each loop and remove directly via list.remove(), an exception will be thrown.