Explain Codes LogoExplain Codes Logo

How to remove a key from HashMap while iterating over it?

java
concurrent-modification-exception
iterator
java-8
Alex KataevbyAlex Kataev·Feb 20, 2025
TLDR
// Safety first! Let's use Iterator's remove() mechanism for clean operation for (Iterator<Map.Entry<KeyType, ValueType>> it = hashMap.entrySet().iterator(); it.hasNext();) { // Remember, don't just remove, check it before you wreck it! if (shouldRemove(it.next().getKey())) it.remove(); }

Harness the power of Iterator from entrySet() of your HashMap to iterate and erase entries during the iterative process, not causing a ConcurrentModificationException. Invoke it.remove() after it.next().

Detailed explanation

Using Iterator for precise and orderly removal

Iterating through a HashMap and simultaneously modifying it can be a precarious task, potentially leading to a ConcurrentModificationException. The Iterator comes to our rescue by offering a safe mechanism to iterate and remove entries during the process.

// Who said a stroll in the park can't be productive? Iterator<Map.Entry<KeyType, ValueType>> it = hashMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<KeyType, ValueType> entry = it.next(); // Save your future-self from debugging headaches, conduct your due diligence before removing! if (shouldRemove(entry.getKey())) it.remove(); }

Utilizing removeIf and lambda expressions

In the realm of Java 8, life becomes a tad easier and our code a lot more readable. A new method removeIf along with lambda expressions allows us to remove entries based on specified conditions in a much more intuitive and concise manner:

// Remove all entries that feel like "Sample", in a world overlooking lettercase hashMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

Efficient clean-up with removeIf and lambdas

The introduction of lambda expressions in Java 8 made it easier than ever to remove entries that fulfill certain conditions. We can meet the conditions at any point during the iteration, which leads to more expressive and concise coding:

// Getting rid of the bad apples in one sweep hashMap.entrySet().removeIf(entry -> entry.getKey().hasBadSmell());

Iterating and filtering with Java Streams

Streams introduced in Java 8 cater to those comfortable with functional programming styles. They can be leveraged to filter and collect entries sans specified keys:

// Gandalf to unwanted keys: "You shall not pass!" hashMap = hashMap.entrySet().stream() .filter(entry -> !unwantedKeys.contains(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Please note, it creates a new HashMap, which may not be performant for large volumes of data.