简体   繁体   中英

Java - HashMap Iteration - Exception

I want to iterate a HashMap like:

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards

 Iterator<Map.Entry<Integer, Integer>> entryItr = map.entrySet().iterator();
 while (entryItr.hasNext()) {
   Map.Entry<Integer, Integer> entry = entryItr.next();
   if (entry.getValue() > 1) {
     entry.setValue(entry.getValue() - 1);
   } else {
     entryItr.remove();
   }
 }

You're removing items from the map as you're iterating through it. This is what's causing the exception.

To get a bit of intuition as to why this is: if your map contains three items and on the first iteration you remove the first item, should the next item be the second, or third? ie should the iteration continue as though the removed item was still there? And if so, how?

You can get around this by using an iterator on the map which safely goes through each element of the map.

You can't remove elements from an existing Set without using Iterator , otherwise, it will throw ConcurrentModificationException

So, place values to a new Map object if(value-1 !=0) as shown below:

        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, Integer> newMap = new HashMap<>();
        Iterator<Integer> iterator =map.keySet().iterator();
        while(iterator.hasNext()) {
            int key = iterator.next();
            int value = map.get(key);
            if(value-1 !=0) {
                newMap.put(key, value-1);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM