Iterate through a HashMap
Here is how to loop through a HashMap
in Java:
To only focus on keys or values, use keySet()
or values()
respectively:
UPDATE** your HashMap while iterating? Employ an Iterator
with remove()
:
Optimised HashMap traversal tips
Remember that entrySet()
offers most efficient traversal if you need both keys and values.
Access the entry.getKey()
for key and entry.getValue()
to fetch value. This saves the computational price of looking up the key twice.
If you only care about keys or values, use keySet()
or values()
respectively. But fetching values using map.get(key)
inside a loop is a performance Bermuda Triangle.
Safe alterations during iteration
To modify the map during iterating, grab the Iterator
from entrySet()
or keySet()
and use iterator.remove()
to avoid being haunted by the spooky ConcurrentModificationException
.
Safe entry removal? Use Iterator!
Trying to cut entries from HashMap
within a forEach
loop is like trying to change tires on a moving car - a ConcurrentModificationException
. To safely chuck entries while iterating, make iterator.remove()
your best friend.
Master-level methods & performance aspects
Java 8 Stream operations
For a compact and functional approach, grab a stream on the party:
Parallel processing with Streams
Bigger the HashMap
, sweeter is the parallel stream. But remember who's watching (thread safety)!
Reduced verbosity with lambdas
Replacing verbose operations on values (method reference
or lambda expression
):
Pitfalls that can burn off your performance wings
Memory leaks
Be careful about the memory leaks. Collecting values inside keySet()
using get()
within loop scope can turn the garbage collector jobless with large data sets.
Inconsistent state on failure
When modifying a map, remember to ensure or revert to a consistent state if an operation goes south.
Was this article helpful?