仅迭代HashMap的值一次

时间:2014-05-14 16:53:34

标签: java collections iterator hashmap

我有一个带有几个条目的HashMap。我想迭代HashMap的所有值。我想在迭代(添加和删除条目)时修改HashMap。这可以通过使用ListIterator来完成。对? 但是新条目会发生什么?他们也会被迭代吗?或者他们会被忽略吗?

谢谢大家。

永旺

1 个答案:

答案 0 :(得分:0)

使用迭代器时无法添加,它将抛出ConcurrentModificationException

你能做什么:

Map<String, String> thingsToAdd = new HashMap<>();

for (Iterator<Map.Entry<String, String>> i = yourMap.entrySet().iterator(); i.hasNext();) {
            Map.Entry<String, String> entry = i.next();

    if (...) { // Add things
        thingsToAdd.put(..);
    }

    if (...) { // Remove things
        i.remove();
    }
}

yourMap.addAll(thingsToAdd);
相关问题