iterate
Map
Java

How do I efficiently iterate over each entry in a Java Map?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, there are several efficient ways to iterate over a Map, depending on your needs. Here are the most common approaches:

1. Using forEach Method (Java 8+)

The forEach method allows you to iterate over each entry concisely and is generally the preferred method for readability and efficiency.

java
1Map<String, Integer> map = new HashMap<>();
2map.put("apple", 1);
3map.put("banana", 2);
4map.put("cherry", 3);
5
6map.forEach((key, value) -> System.out.println(key + ": " + value));

2. Using entrySet() with Enhanced for Loop

The entrySet() method provides a set of Map.Entry objects, each containing a key-value pair. This method is efficient and commonly used.

java
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

3. Using entrySet().iterator() with a While Loop

If you need more control, such as removing entries while iterating, using an explicit iterator with entrySet() is a good choice.

java
1Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
2while (iterator.hasNext()) {
3    Map.Entry<String, Integer> entry = iterator.next();
4    System.out.println(entry.getKey() + ": " + entry.getValue());
5    // iterator.remove(); // Uncomment if you need to remove entries
6}

4. Using keySet() or values() if Only Keys or Values are Needed

If you only need keys or values, you can iterate over keySet() or values() directly.

Iterating over Keys Only

java
for (String key : map.keySet()) {
    System.out.println("Key: " + key);
}

Iterating over Values Only

java
for (Integer value : map.values()) {
    System.out.println("Value: " + value);
}

Summary

  • forEach is preferred for simplicity and readability in Java 8+.
  • entrySet() with a for loop is efficient and commonly used.
  • Iterator with entrySet() is useful when modifying the map while iterating.
  • Use keySet() or values() if you only need keys or values.

Course illustration
Course illustration

All Rights Reserved.