Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating through a HashMap while removing AND updating the collection

I have a count map where I keep track of the numbers of characters from a string. I want to iterate over that map, decrement the currently visited character count AND remove it if it reaches zero.

How can that be done in Java?

HashMap<Character, Integer> characterCount = new HashMap<>();
characterCount.put('a', 2);
characterCount.put('b', 1);
characterCount.put('c', 1);

Iterator<Map.Entry<Character, Integer>> iterator = characterCount.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<Character, Integer> entry = iterator.next();

    // Decrement the chosen character from the map
    if (entry.getValue() == 1) {
        iterator.remove();
    } else {
        characterCount.put(entry.getKey(), entry.getValue() - 1);
    }

    // Call some logic the relies on the map with the remaining character count.
    // I want the characterCount.size() to return zero when there is no character with count > 0
    doSomeLogic(characterCount);

    // Restore the character to the map
    characterCount.put(entry.getKey(), entry.getValue());
}

The above code results in a ConcurrentModificationException.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since Map#entrySet returns a view of the mappings in the map, directly set the value of the Entry to update it.

if (entry.getValue() == 1) {
    iterator.remove();
} else {
    entry.setValue(entry.getValue() - 1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading