Explain Codes LogoExplain Codes Logo

Iterate through a HashMap

java
hashmap
collections
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 25, 2025
TLDR

Here is how to loop through a HashMap in Java:

// Using entrySet() for keys and values for (Map.Entry<K, V> entry : map.entrySet()) { // Party with a key-value pair }

To only focus on keys or values, use keySet() or values() respectively:

// Only keys for (K key : map.keySet()) { /* Act on key */ } // Only values for (V value : map.values()) { /* Act on value */ }

UPDATE** your HashMap while iterating? Employ an Iterator with remove():

// Make Iterator your partner in crime Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); // Iterate like you are searching for treasure while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if ( /* Removal condition */ ) { it.remove(); // Voila! Safe removal during iteration } }

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:

// Netflix streaming, the Java version map.entrySet().stream().forEach(entry -> { /* Enjoy the entry */ });

Parallel processing with Streams

Bigger the HashMap, sweeter is the parallel stream. But remember who's watching (thread safety)!

// Release the processing kraken! map.entrySet().parallelStream().forEach(entry -> { /* Engage with entry */ });

Reduced verbosity with lambdas

Replacing verbose operations on values (method reference or lambda expression):

// Freedom from braces! map.values().forEach(System.out::println);

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.