How to Loop Through HashMap in Java
The Challenge
Iterate through keys, values, or key-value pairs in a HashMap!
Solutions
Method 1: Using For-Each with entrySet()
import java.util.HashMap;
import java.util.Map;
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Output:
// Alice: 95
// Bob: 87
// Charlie: 92Method 2: Loop Through Keys Only
for (String name : scores.keySet()) {
System.out.println(name + ": " + scores.get(name));
}Method 3: Loop Through Values Only
for (Integer score : scores.values()) {
System.out.println("Score: " + score);
}Method 4: Using forEach() with Lambda
scores.forEach((name, score) ->
System.out.println(name + ": " + score)
);Method 5: Using Iterator
import java.util.Iterator;
Iterator<Map.Entry<String, Integer>> it = scores.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}Did You Know?
Using entrySet() is more efficient than keySet() when you need both keys and values, because it avoids extra get() calls!
Pro Tip
The lambda forEach() method is the most concise and modern approach for iterating through HashMaps!
Real-World Use Cases
- Configuration: Process settings key-value pairs
- Caching: Iterate through cached data
- Statistics: Display frequency counts
- User data: Process user attributes
›Short versionOpen if you only have a minute.
- entrySet gives the key and the value together. keySet plus get hashes the key again.
- get returns null both for a missing key and for a stored null value.
- HashMap iteration order is not insertion order and not sorted order.
- Adding or removing entries inside a for-each throws ConcurrentModificationException.
Loop a HashMap
Iterate keys, values, or pairs, using the view that matches what the body needs.
Working approach
- Use entrySet when the body reads both sides.
- Use values when the key is irrelevant.
- Use LinkedHashMap or TreeMap when the order is part of the contract. Do not depend on HashMap order.
Walk the sample
- Map Alice to 95, Bob to 87
- entrySet yields each pair
- The print order is not part of the result
The trap
A loop over keySet that then calls get cannot tell a missing key from a null value, and it does a second lookup the entry already avoided.
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
String name = entry.getKey();
Integer score = entry.getValue();
// score may be null. Do not use entry order as a sort.
}Why prefer entrySet when the loop needs the value?
The entry already holds it. keySet plus get hashes again.
get also returns null when the key is absent and when the value was stored as null. During iteration the key is present, but a later refactor that calls get on a key from outside the map loses that distinction. Do not structurally modify the map in the loop body.
Time O(n) in the number of entries, extra space O(1) for the loop.
Easy to get wrong
- Looking the key up again when the entry is in hand.
- Asserting that the print order matches insertion order.