Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through/Updating HashMap [duplicate]

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?

like image 509
Lemonio Avatar asked Oct 04 '22 14:10

Lemonio


2 Answers

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);
}
like image 95
Jean Logeart Avatar answered Oct 12 '22 07:10

Jean Logeart


Use Map.Entry.setValue to change the value of the mapping. If you want to remove the mapping, use setValue(null) use an Iterator.

like image 32
Jeffrey Avatar answered Oct 12 '22 07:10

Jeffrey