Traversing Hash Maps

Tue, Aug 29, 2023 2-minute read

In Java, you can traverse a HashMap in several ways. Here are some of them:

1. Using For-Each Loop with entrySet()

You can use the entrySet() method to get a set view of the mappings contained in the map. This set contains instances of the Map.Entry class, each representing a key-value pair in the map.

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

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

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

2. Using For-Each Loop with keySet()

You can use the keySet() method to get a set view of the keys contained in the map, and then use these keys to look up the values.

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

3. Using For-Each Loop with values()

If you are only interested in the values and not the keys, you can use the values() method to get a collection view of the values contained in the map.

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

4. Using Iterator with entrySet()

You can use an Iterator to loop through the set view returned by entrySet().

import java.util.Iterator;

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());
}

5. Using Iterator with keySet()

Similarly, you can use an Iterator to loop through the set view returned by keySet().

Iterator<String> keyIterator = map.keySet().iterator();
while (keyIterator.hasNext()) {
    String key = keyIterator.next();
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

6. Using Java 8 Streams

You can also use Java 8 Streams to traverse a HashMap.

map.entrySet().stream().forEach(e -> System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue()));

7. Using forEach method

From Java 8 onwards, you can use the forEach method provided by the Map interface to loop through each key-value pair.

map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));

These are some of the common ways to traverse a HashMap in Java. Choose the one that best fits your needs.