Java.Collections.How to iterate over all key-value pairs in a Map?

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

ApproachCode Example
Enhanced for loopfor (Map.Entry<K,V> e : map.entrySet())
IteratorIterator<Map.Entry<K,V>> over entrySet()
Lambdamap.forEach((k, v) -> ...)
Streammap.entrySet().stream()...
This entry was posted in Без рубрики. Bookmark the permalink.