如何替换 java 地图中的所有键?

How to replace ALL keys in java map?

我想替换地图中的键。

我有以下代码:

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();
}

我想用key实现map

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

如果我在循环 map.put(next.getKey() + next.getValue(), next.getValue()); 中使用,它将导致 ConcurrentModificationException

为避免 ConcurrentModificationException,您需要将新的 key/value 对添加到单独的地图中,然后使用 putAll 将该地图添加到原始地图中。

    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);