How to iterate through a HashMap in Java?

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() vs keySet():
  • entrySet() is more efficient for iterating over both keys and values because it avoids redundant lookups (e.g., map.get(key)).
  • keySet() requires a map.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. Use Iterator.remove() instead.
  • Ordering:
  • HashMap does not guarantee iteration order. Use LinkedHashMap for insertion-order iteration or TreeMap for sorted order.

Summary

MethodUse CaseEfficiencyModifiable During Iteration?
entrySet() with for-loopAccess keys and valuesHighNo (use Iterator instead)
Iterator with entrySet()Safe removal during iterationHighYes
keySet()/values()Iterate keys or values onlyMediumNo
Java 8 forEach/StreamsConcise syntax (Java 8+)HighNo

Example:

// Most common approach (entrySet + for-loop)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Leave a Reply

Your email address will not be published. Required fields are marked *