Question
What is the best way to remove elements from a list while iterating over it in Java?
for (String fruit : list) {
if("banana".equals(fruit))
list.remove(fruit);
System.out.println(fruit);
}
Answer
When iterating over a list in Java and attempting to modify it by removing elements, you may encounter a ConcurrentModificationException. This issue arises because the iterator detects that the list structure has changed during iteration, making it unsafe to continue. Here, we'll discuss safe methods to remove items from a list while iterating over it.
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if ("banana".equals(fruit)) {
iterator.remove(); // Safely remove using the iterator
}
}
Causes
- Using an enhanced for-loop (for-each) directly on a list while modifying the list structure.
- Not using an explicit Iterator when performing modifications.
Solutions
- Use an Iterator explicitly to remove elements safely while iterating.
- Use the Java 8 Stream API to filter items and create a new collection which excludes the undesired elements.
- Collect elements to be removed in a separate list then remove them after the iteration.
Common Mistakes
Mistake: Using a for-each loop for removal instead of an iterator.
Solution: Always use an iterator when you need to remove elements during iteration.
Mistake: Removing items from the list within the for-each block.
Solution: Switch to using an explicit Iterator to prevent ConcurrentModificationException.
Helpers
- Java remove element
- ConcurrentModificationException
- Java Iterator example
- remove item from list Java
- safe list iteration Java