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();
}
}
相关文章