0
0
JavaHow-ToBeginner · 3 min read

How to Iterate HashMap in Java: Syntax and Examples

To iterate a HashMap in Java, you can use a for-each loop over the entrySet() to access keys and values together. Alternatively, you can iterate over the keySet() or values() collections depending on your needs.
📐

Syntax

Here are common ways to iterate a HashMap<K, V>:

  • Using entrySet(): Loop through each key-value pair.
  • Using keySet(): Loop through keys and get values inside the loop.
  • Using values(): Loop through values only.
java
for (Map.Entry<K, V> entry : map.entrySet()) {
    K key = entry.getKey();
    V value = entry.getValue();
    // use key and value
}

for (K key : map.keySet()) {
    V value = map.get(key);
    // use key and value
}

for (V value : map.values()) {
    // use value only
}
💻

Example

This example shows how to create a HashMap and iterate it using entrySet() to print keys and values.

java
import java.util.HashMap;
import java.util.Map;

public class IterateHashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 5);
        map.put("orange", 2);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
Output
Key: apple, Value: 3 Key: banana, Value: 5 Key: orange, Value: 2
⚠️

Common Pitfalls

Common mistakes when iterating a HashMap include:

  • Using map.get(key) inside a loop over keySet() which is less efficient than using entrySet().
  • Modifying the map (adding or removing entries) while iterating without using an Iterator, which causes ConcurrentModificationException.
  • Assuming the order of iteration is the same as insertion; HashMap does not guarantee order.
java
import java.util.HashMap;
import java.util.Map;

public class PitfallExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 1);
        map.put("b", 2);

        // Inefficient way: calls get() for each key
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }

        // Correct way: use entrySet()
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
Output
a: 1 b: 2 a: 1 b: 2
📊

Quick Reference

Summary of iteration methods:

MethodDescriptionUse Case
entrySet()Iterates key-value pairs togetherBest for accessing both keys and values efficiently
keySet()Iterates keys onlyUse when you need keys and can get values separately
values()Iterates values onlyUse when keys are not needed

Key Takeaways

Use entrySet() to efficiently iterate keys and values together in a HashMap.
Avoid modifying a HashMap while iterating without using an Iterator to prevent errors.
HashMap iteration order is not guaranteed; use LinkedHashMap if order matters.
Iterating keySet() and calling get() inside the loop is less efficient than entrySet().