Let’s wrap it up with the classic: iterating over all key-value pairs in a Map<K, V>
.
✅ 1. Enhanced for loop using entrySet()
(most common way)
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
map.entrySet()
returns a Set<Map.Entry<K, V>>
Each Map.Entry
holds both a key and a value.
✅ 2. Using an Iterator over entrySet()
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
- Gives you more control (e.g. you can call
iterator.remove()
)
✅ 3. Java 8+ forEach()
with lambda
map.forEach((key, value) -> System.out.println("Key = " + key + ", Value = " + value));
- Very clean and expressive.
- Recommended when using Java 8+ for clarity and brevity.
✅ 4. Stream API (for filtering, mapping, collecting)
map.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));
Great for more complex logic (like filtering, grouping, etc.)
🧠 TL;DR
Approach | Code Example |
---|---|
Enhanced for loop | for (Map.Entry<K,V> e : map.entrySet()) |
Iterator | Iterator<Map.Entry<K,V>> over entrySet() |
Lambda | map.forEach((k, v) -> ...) |
Stream | map.entrySet().stream()... |