Java HashMap Adds New Entry During Iteration

In hashmap

map = new HashMap<String,String>();

it = map.entrySet().iterator();
while (it.hasNext())
{
    entry = it.next();
    it.remove(); //safely remove a entry
    entry.setValue("new value"); //safely update current value
    //how to put new entry set inside this map
    //map.put(s1,s2); it throws a concurrent access exception

}

When I try to add a new entry to display it, it throws ConcurrentModificationException. To remove and update iterator safely removes methods. How to add a new record during iteration?

+4
source share
3 answers

, . HashMap , . , , . . , , , . , , .

- .

Map<String,String> values = ...

Map<String,String> temp = new HashMap<>();
for (Entry<String,String> entry : values.entrySet()) {
    if ("some value".equals(entry.getValue()) {
        temp.put(entry.getValue(), "another value");
    }
}
values.putAll(temp);
+4

ConcurrentHashMap . HashMap , ConcurrentModificationException, . ConcurrentHashMap , , , .

0

:

map = new HashMap<String,String>();

it = map.entrySet().iterator();
while (it.hasNext())
{
    entry = it.next();
    entry.setValue("new value"); // update current value
}

HashMap, . , . , .

0

Source: https://habr.com/ru/post/1569805/


All Articles