在 Java 中迭代和从 Hashtable 中删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2351331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over and deleting from Hashtable in Java
提问by Mohit BAnsal
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 哈希表,想遍历表中的所有值并在迭代时删除特定的键值对。
How may this be done?
如何做到这一点?
采纳答案by Adamski
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.
您需要使用显式java.util.Iterator
来迭代Map
的条目集,而不是能够使用 Java 6 中提供的增强的 For 循环语法。以下示例迭代 a Map
of Integer
,String
对,删除任何Integer
键为 null 或等于的条目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();
}
}
回答by Scharrels
You can use a temporary deletion list:
您可以使用临时删除列表:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
您可以在Java API 中找到有关 Hashtable 方法的更多信息
回答by polygenelubricants
So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:
那么您知道要提前删除的键值对吗?这样做就更清楚了,然后:
table.delete(key);
for (K key: table.keySet()) {
// do whatever you need to do with the rest of the keys
}
回答by mostar
You can use Enumeration
:
您可以使用Enumeration
:
Hashtable<Integer, String> table = ...
Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
Integer key = enumKey.nextElement();
String val = table.get(key);
if(key==0 && val.equals("0"))
table.remove(key);
}