温馨提示×

hashmap的遍历中如何优雅删除元素

小樊
85
2024-07-11 18:48:36
栏目: 编程语言

在遍历HashMap时,不能直接对HashMap进行删除操作,因为这会导致ConcurrentModificationException异常。因此,通常需要借助一个临时的集合来保存需要删除的元素的key,待遍历完成后再进行删除操作。

以下是一种优雅的方法来删除HashMap中的元素:

Map<Integer, String> map = new HashMap<>();
map.put(1, "apple");
map.put(2, "banana");
map.put(3, "orange");

List<Integer> keysToRemove = new ArrayList<>();

for (Integer key : map.keySet()) {
    if (条件满足) {
        keysToRemove.add(key);
    }
}

for (Integer key : keysToRemove) {
    map.remove(key);
}

在第一个循环中,我们遍历HashMap的key集合,并根据需要删除的条件将需要删除的key保存在一个临时的集合中。在第二个循环中,我们再遍历临时集合,逐个删除HashMap中对应的元素。

这样可以避免ConcurrentModificationException异常,同时实现了优雅地删除HashMap中的元素。

0