我知道有几种遍历哈希表的方法,但在遍历时修改哈希表,有什么好的方法(除了创建一个新的哈希表并且去掉旧的哈希表)?
我想要像下面这样:
for (Map.Entry<String, Integer> entry : wordcounts.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
if(blacklist.contains(key))
//remove key/value for that key from wordcounts
if(mappings.contains(key))
//change key in wordcounts from one string to another based on the key's value in a <string,string> map (mappings)
}
我能在遍历地图的过程中修改它吗?我必须使用迭代器吗?
Iterator
在遍历时删除条目。如果要更改键值,则需要创建一个新的Map
,并复制不变的值或修改并插入更改的值。如果在添加到新Map
时从旧的Map
中删除它们,则时间和内存成本并不太大。 - Lee Meador