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

前端 未结 7 1022
眼角桃花
眼角桃花 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:19

    Iterating over a Map and adding entries at the same time will result in a ConcurrentModificationException for most Map classes. And for the Map classes that don't (e.g. ConcurrentHashMap) there is no guarantee that an iteration will visit all entries.

    Depending on exactly what it is you are doing, you may be able to do the following while iterating:

    • use the Iterator.remove() method to remove the current entry, or
    • use the Map.Entry.setValue() method to modify the current entry's value.

    For other types of change, you may need to:

    • create a new Map from the entries in the current Map, or
    • build a separate data structure containing changes to be made, then applied to the Map.

    And finally, the Google Collections and Apache Commons Collections libraries have utility classes for "transforming" maps.

提交回复
热议问题