Iterating over and deleting from Hashtable in Java(Java中的Hashtable迭代和删除)
问题描述
我在 Java 中有一个 Hashtable,想要遍历表中的所有值并在迭代时删除特定的键值对.
I have a Hashtable in Java and want to iterate over all the values in the table and delete a particular key-value pair while iterating.
如何做到这一点?
推荐答案
您需要使用显式 java.util.Iterator 来迭代 Map 的条目设置而不是能够使用 Java 6 中可用的增强的 For 循环语法.以下示例遍历 Integer、String 的 Map对,删除 Integer 键为 null 或等于 0 的任何条目.
You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
这篇关于Java中的Hashtable迭代和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的Hashtable迭代和删除
基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
