【问题标题】:How to replace ALL keys in java map? [duplicate]如何替换java map中的所有键? [复制]
【发布时间】:2016-11-04 00:27:59
【问题描述】:

我想替换地图中的键。

我有以下代码:

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

我想用keys实现map

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

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

【问题讨论】:

  • 我们是否保证地图中不存在新密钥?另外,您在编写代码时是否遇到任何具体问题?
  • 这是某种跟踪论坛审核的测试帐户吗?
  • @Pshemo 是的,这是有保证的
  • @pandaadb 真的吗?肯定会替换之前的value
  • @arizzle concurrentModificationException

标签: java dictionary iterator add


【解决方案1】:

为避免出现ConcurrentModificationException,您需要将新的键/值对添加到单独的映射中,然后使用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);

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2020-07-26
    • 2018-03-10
    相关资源
    最近更新 更多