How to remove a key from HashMap while iterating over it?
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.
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:
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:
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:
Please note, it creates a new HashMap
, which may not be performant for large volumes of data.
Was this article helpful?