-1

I want to replace keys in my map.

I have the following code:

Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
map.put("e", "5");
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Object> next = iterator.next();
    Object o = next.getValue();
    //how to add new element ?
    //...
    iterator.remove();
}

I want to achieve map with keys

a1->1
b2->2
c3->3
d4->4
e5->5

If I use in loop map.put(next.getKey() + next.getValue(), next.getValue()); it will lead to ConcurrentModificationException.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

3

To avoid a ConcurrentModificationException, you need to add the new key/value pairs to a separate map, and then use putAll to add that map into the original one.

    Map<String, Object> newMap = new HashMap<>();
    while (iterator.hasNext()) {
        Map.Entry<String, Object> entry = iterator.next();
        iterator.remove();
        newMap.put(...);  // Whatever logic to compose new key/value pair.
    }
    map.putAll(newMap);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243