Write a Java Program to Iterate over a HashMap

Iterating over a HashMap is a common operation in Java programming.

A HashMap is a collection that stores key-value pairs, and it is an efficient data structure for lookup operations.

In this tutorial, we will discuss how to iterate over a HashMap in Java.


Java provides several ways to iterate over a HashMap.

Let’s explore some of these methods.

Using the keySet() method

The keySet() method returns a set of all keys in the HashMap.

We can use a for-each loop to iterate over the keys and retrieve their values from the HashMap.

Here’s an example code snippet:

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);

for (String key : hashMap.keySet()) {
    Integer value = hashMap.get(key);
    System.out.println(key + " = " + value);
}

In the above code, we first create a HashMap and populate it with some key-value pairs.

Then, we iterate over the key set using a for-each loop and retrieve the corresponding value for each key using the get() method.

Using the entrySet() method

The entrySet() method returns a set of all key-value pairs in the HashMap.

We can use a for-each loop to iterate over the entry set and retrieve both the key and value of each pair.

Here’s an example code snippet:

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);

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

In the above code, we first create a HashMap and populate it with some key-value pairs.

Then, we iterate over the entry set using a for-each loop and retrieve both the key and value of each pair using the getKey() and getValue() methods of the Map.Entry interface.

Using forEach() method (Java 8)

In Java 8 and later versions, we can use the forEach() method of the HashMap class to iterate over the key-value pairs.

Here’s an example code snippet:

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);

hashMap.forEach((key, value) -> System.out.println(key + " = " + value));

In the above code, we first create a HashMap and populate it with some key-value pairs.

Then, we call the forEach() method of the HashMap class, which takes a lambda expression that specifies the action to be performed on each key-value pair.


Conclusion

In this tutorial, we have discussed three methods to iterate over a HashMap in Java: using the keySet() method, using the entrySet() method, and using the forEach() method (Java 8).

These methods are efficient and easy to use, and you can choose the one that best fits your requirements.