在遍历 HashMap 的时候使用迭代器的 remove 方法删除元素示例
假设有一个 HashMap<String, Integer>,我们要删除值为0的所有元素,可以使用迭代器的 remove() 方法来实现:
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 0);
map.put("c", 2);
map.put("d", 0);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
if (entry.getValue() == 0) {
iterator.remove();
}
}
System.out.println(map); // 输出:{a=1, c=2}
上述代码通过遍历 HashMap 的 entrySet(),获取每个键值对,然后判断值是否为0,如果是则使用迭代器的 remove() 方法删除该元素。最后输出剩余的元素
原文地址: https://www.cveoy.top/t/topic/hhFc 著作权归作者所有。请勿转载和采集!