What is the best way to iterate over a HashMap in Java?

The most efficient general way is to loop over entrySet(), because each entry gives you both the key and the value without a second lookup. Since Java 8, map.forEach((k, v) -> ...) is a shorter alternative, and streams are useful when you also filter or sort.

Key Points: • entrySet(): one pass, key and value together. This is the best default. • keySet() followed by map.get(key) does an extra hash lookup for every key, so avoid it when you need the values. • values() when you only need the values. • map.forEach((k, v) -> ...) is concise and works the same way as entrySet(). • To remove entries while iterating, use entrySet().removeIf() or the iterator's remove(), never map.remove() inside the loop. • To iterate in sorted key order, use a TreeMap or stream the entries with sorted(Map.Entry.comparingByKey()).

Code Example:

import java.util.LinkedHashMap;
import java.util.Map;

public class IterateMap {

    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();
        stock.put("laptop", 12);
        stock.put("phone", 0);
        stock.put("tablet", 7);

        // 1. entrySet (recommended)
        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }

        // 2. forEach with a lambda (Java 8+)
        stock.forEach((item, qty) -> System.out.println(item + " -> " + qty));

        // 3. Streams when you also filter or sort
        stock.entrySet().stream()
             .filter(e -> e.getValue() > 0)
             .sorted(Map.Entry.comparingByValue())
             .forEach(e -> System.out.println("In stock: " + e.getKey()));

        // Remove while iterating
        stock.entrySet().removeIf(e -> e.getValue() == 0);
        System.out.println("After removeIf: " + stock);
    }
}

Output:

laptop = 12 phone = 0 tablet = 7 laptop -> 12 phone -> 0 tablet -> 7 In stock: tablet In stock: laptop After removeIf: {laptop=12, tablet=7}

Good to Know: The example uses a LinkedHashMap so the output order is predictable. With a plain HashMap the same code works, but the iteration order isn't guaranteed and can change between Java versions or as the map grows.

Interview Tip: A concise interview answer is:

"I iterate over entrySet, because it gives the key and value together in one pass, whereas keySet plus get does an extra lookup for every key. In modern code map.forEach with a lambda is shorter, streams help when I also filter or sort, and to remove entries during iteration I use entrySet().removeIf()."

Previous question: When is ArrayList faster than LinkedList, and is LinkedList ever the better choice?

Next question: What is the difference between fail-fast and fail-safe iterators in Java?

More Java Collections interview questions

All Java Collections questions