We have a method that iterates over a Collection. We want to remove certain elements from that collection inside the loop in which certain criteria are matched, how should we code this scenario?

By | March 5, 2023

If you want to remove elements from a collection while iterating over it, you should use an Iterator instead of a for-each loop. The reason for this is that the for-each loop uses an implicit iterator, which does not allow for modification of the collection during iteration. Here’s an example of how to do this:

Iterator<Type> iterator = collection.iterator();

while (iterator.hasNext()) {

    Type element = iterator.next();

    if (someCondition(element)) {




In this code, we first obtain an iterator for the collection using the iterator() method. We then iterate over the collection using the hasNext() and next() methods of the iterator. Inside the loop, we check if the current element satisfies some condition using the same condition () method. If the condition is true, we remove the element from the collection using the remove() method of the iterator.

By using the remove() method of the iterator instead of the remove() method of the collection, we can safely remove elements from the collection without causing a ConcurrentModificationException. This is because the iterator keeps track of the current state of the collection and can modify it safely.

You may also like:

What are common multi-threading issues faced by Java Developers?
What are different states of a Thread? What does those states tell us?
What happens when wait() & notify() methods are called?
What is difference between sleep(), yield() and wait() method?
What is difference between Callable and Runnable Interface?

Leave a Reply

Your email address will not be published. Required fields are marked *