Week 154 — How can one safely remove elements while iterating over a collection?
Question of the Week #154
How can one safely remove elements while iterating over a collection?
6 Replies
Most collections don't allow modifying them while they are being iterated over using an
Iterator/for-each loop. These collections would throw a ConcurrentModificationException when the next element is retrieved.
If removing the current element is necessary during iteration, the Iterator#remove method can be used:
However, there are cases where this is not applicable as e.g. elements other than the current one need to be removed. In cases like this, it may be possible to use an indexed loop and make sure to update the index as appropriate:
However, this is only possible with collections that support indexed iterations (typically only Lists) and correctly updating the index may be complicated.In many cases, it is also possible to use methods provided by the collection API like
removeIf:
Similarly, it is possible to just create an auxiliary collection containing the elements to remove and removing them after iteration:
📖 Sample answer from dan1st
In Java, to safely remove elements while iterating over a collection, use an Iterator with its remove() method or the removeIf method. Removing elements directly in a for-each loop can cause a ConcurrentModificationException.
that's my answer
⭐ Submission from mrmisha001
iterator.
remove next item while hasNext
Submission from ziberlit
use Iterator.remove()
Submission from 4b_wang