I know there are several ways to iterate through a hashmap, but what is a good way to modify a hashmap as you go along (other than just creating a new hashmap and getting rid of the old one)
I want something like
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)
}
Will it be possibly for me to modify my map while I'm going through it? Do i have to use an iterator?
Take advantage of the map: go through your other collections first and do your operations.
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 use an setValue(null)
Iterator
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With