Search This Blog

Breaking

Tuesday, 16 May 2023

May 16, 2023

[Java8] Avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it

 Have you ever removed some element while iterating over the arrayList or collection objects? If yes, Have you encountered "ConcurrentModificationException" at run time.

If your answer is yes, it means you also tried to avoid creating another list which can hold items which salsify your condition.

As per java doc:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

To understand it from code point, we can check below code:   


List<String> values = new ArrayList<>();
values.add("A");
values.add("b-");
values.add("c");
values.add("D-");
for(String value: values) {
if(value.endsWith("-")) {
values.remove(value);
}


Here we are trying to remove value which is ending with "-" from the list "Values".

What we tried to do here, is to iterate the list elements and checking the condition, if satisficed, removing list items, which reduces the list size.

If you will debug this code, you will see:

When the first condition satisfies and it reduces the size of the list, and at that moment, when it reaches to for loop iteration with the updated list size, it throws ConcurrentModificationException.

So to avoid, this exception in java 8, we can use removeIf method.

values.removeIf(value -> value.endsWith("-"));
System.out.println("Values are: " + values);


removeIf() Removes all of the elements from the collection that satisfy the given predicate. If you will see it's implementation, it is based on the iterator.