To iterate through a HashMap
in Java, there are several methods depending on whether you need keys, values, or entries (key-value pairs). Below are the most common and efficient approaches:
1. Iterate Over Entries (Key-Value Pairs)
Best for: Accessing both keys and values during iteration.
Methods:
a. Using entrySet()
with Enhanced For-Loop
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
Output:
Apple: 10
Banana: 20
Cherry: 30
b. Using Iterator
(Supports Removal During Iteration)
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
// iterator.remove(); // Safely remove the current entry
}
2. Iterate Over Keys Only
Best for: When you only need keys.
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
3. Iterate Over Values Only
Best for: When you only need values.
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
4. Java 8+ Methods
a. Using forEach()
with Lambda
map.forEach((key, value) ->
System.out.println(key + ": " + value)
);
b. Using Streams
map.entrySet().stream()
.forEach(entry ->
System.out.println(entry.getKey() + ": " + entry.getValue())
);
5. Performance Considerations
entrySet()
vskeySet()
:entrySet()
is more efficient for iterating over both keys and values because it avoids redundant lookups (e.g.,map.get(key)
).keySet()
requires amap.get(key)
to retrieve values, which adds overhead (O(n) time for each key in the worst case).
6. Common Pitfalls
- Concurrent Modification:
- Do not modify the
HashMap
(e.g., remove/add entries) while iterating with a for-loop. UseIterator.remove()
instead. - Ordering:
HashMap
does not guarantee iteration order. UseLinkedHashMap
for insertion-order iteration orTreeMap
for sorted order.
Summary
Method | Use Case | Efficiency | Modifiable During Iteration? |
---|---|---|---|
entrySet() with for-loop | Access keys and values | High | No (use Iterator instead) |
Iterator with entrySet() | Safe removal during iteration | High | Yes |
keySet() /values() | Iterate keys or values only | Medium | No |
Java 8 forEach /Streams | Concise syntax (Java 8+) | High | No |
Example:
// Most common approach (entrySet + for-loop)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}