How to avoid ConcurrentModificationException when iterating over a map and changing values?

前端 未结 7 1015
眼角桃花
眼角桃花 2020-12-06 09:46

I\'ve got a map containing some keys (Strings) and values (POJOs)

I want to iterate through this map and alter some of the data in the POJO.

The current code

7条回答
  •  北海茫月
    2020-12-06 10:22

    For such purposes you should use the collection views a map exposes:

    • keySet() lets you iterate over keys. That won't help you, as keys are usually immutable.
    • values() is what you need if you just want to access the map values. If they are mutable objects, you can change directly, no need to put them back into the map.
    • entrySet() the most powerful version, lets you change an entry's value directly.

    Example: convert the values of all keys that contain an upperscore to uppercase

    for(Map.Entry entry:map.entrySet()){
        if(entry.getKey().contains("_"))
            entry.setValue(entry.getValue().toUpperCase());
    }
    

    Actually, if you just want to edit the value objects, do it using the values collection. I assume your map is of type :

    for(Object o: map.values()){
        if(o instanceof MyBean){
            ((Mybean)o).doStuff();
        }
    }
    

提交回复
热议问题