Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove and add elements to TreeMap while iterating?

Tags:

java

treemap

I want to write code like this -

for (Map.Entry<Long, Integer> e : map.entrySet()){
    map.remove(k);
    map.put(x, value);
}

but I got java.util.ConcurrentModificationException I tried to use Iterator also but I got the same Exception

like image 712
Mahmoud Hanafy Avatar asked May 19 '13 16:05

Mahmoud Hanafy


People also ask

Can we remove element from map while iterating?

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.

How do you remove an element while iterating?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

How do you remove elements from TreeMap?

TreeMap. remove() is an inbuilt method of TreeMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.

Can we add a new entry to HashMap while iterating?

You need to use ConcurrentHashMap to add elements while iterating the collection. HashMap uses fail-fast iterator, which throws ConcurrentModificationException when the collection is updated while iterating.


1 Answers

Iterate over a copy and you can add/remove just fine:

for (Map.Entry<Long, Integer> e : new LinkedHashMap<Long, Integer>(map).entrySet()){
    map.remove(k);
    map.put(x, value);
}

It's not even any more lines of code, because the copy ims made in-line via the copy constructor. LinkedHashMap was chosen to preserve iteration order (if that matters).

like image 84
Bohemian Avatar answered Oct 21 '22 11:10

Bohemian