Iterating through/Updating HashMap
This question already has an answer here:
利用地图:首先浏览其他收藏并进行操作。
for(String blacklisted : blacklist) {
wordcounts.remove(blacklisted);
}
for(String mapping : mappings) {
String oldKey = // get old key
String value = wordcounts.get(oldKey);
wordcounts.remove(oldKey);
wordcounts.put(mapping, value);
}
Use Map.Entry.setValue
to change the value of the mapping. If you want to remove the mapping, use setValue(null)
use an Iterator
.
Don't try to remove items during the iteration or you'll get an exception out of the iterator. Best bet is to either
a) clone the map by iterating/copying into a new map or b) keeping track as you go along of items to be removed and removing them after you're done iterating.
If you're changing keys, same thing applies.. keep track as you go and do the remove/add after you're done iterating.
If you're just changing values, just go for it.
链接地址: http://www.djcxy.com/p/17982.html上一篇: 在hashmap中查找n个最大值
下一篇: 迭代/更新HashMap