How to Iterate Through a Map in Java

In this article, we will explore how to Iterate through a Map in Java. We will start with a simple use case and will explore how we can do this using Java 8 Stream API.

 

How to Iterate Through a Map in Java

Iterating through Java Map is very common tasks and we face this tasks daily basis. Java Map API provides keySet(), valueSet() or entrySet() option to fetch content/data from the Map. The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to get a reference to a map entry is from the iterator of this collection view. These Map.Entry objects are valid only for the duration of the iteration.Entry.getKey() returns the key corresponding to this entry. Let’s explore different options to Iterate through a Map in Java. With Java 8, we can also use the forEach method to iterate through a Map.

To summarize, here are the different options to Iterate through a Map in Java.

  1. Using forEach method.
  2. Using iterator.
  3. Using for loop.

 

1. Iterate Through a Map Using Java 8

Java 8 came with lots of features and enhancements. With Java 8, forEach method accepts lambda expressions and also provides the option to use the new Stream API.

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

public class IterateMapExample {

    public static void main(String[] args) {
        Map < String, String > sampleMap = new HashMap < String, String > ();
        sampleMap.put("one", "one");
        sampleMap.put("two", "two");
        sampleMap.put("three", "three");
        sampleMap.put("four", "four");
        sampleMap.put("five", "five");
        sampleMap.put("six", "six");

        //iterate using Java8
        sampleMap.forEach(
            (k, v) - > System.out.println("key: " + k + " value: " + v)
        );

        //Using Java stream API
        sampleMap.entrySet().stream().forEach((entry) - > {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " :: " + value);
        });

    }
}

 

2.  Iterate Using for Loop

If you are not using the Java 8, we can use the for loop for iterate through the following:

  1. Iterate both keys and values.
  2. Only keys.
  3. Values only.

The map.entrySet() will return a set view of the mapped values. We can use the getKeys() and getValues() method to get the key-value pairs from the map view. Let’s see how to Iterate through a Map’s keys and values using for loop.

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

public class IterateMapExample {

    public static void main(String[] args) {
        Map < String, String > sampleMap = new HashMap < String, String > ();
        sampleMap.put("one", "one");
        sampleMap.put("two", "two");
        sampleMap.put("three", "three");
        sampleMap.put("four", "four");
        sampleMap.put("five", "five");
        sampleMap.put("six", "six");

        for (Map.Entry < String, String > entry: sampleMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            // use keys and values
            System.out.println(key + " :: " + value);
        }
    }
}

 

2.1. Iterate Map keys only

In case, you are only interested to get the keys out of the map.

for(String key :sampleMap.keySet()){
           System.out.println(key);
}

 

2.2. Iterate Map Values only

for(String key :sampleMap.values()){
           System.out.println(key);
}

 

3.  Using Iterator

In this code, we are using Iterator to go through map values using a while loop.

public void iterator(Map<String, String> map){
    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
    while(iterator.hasNext()){
        Map.Entry<String, String> entry = iterator.next();
        System.out.println(entry.getKey()+" :" + entry.getValue());
    }
}

 

4.  Performance

For small map size (<=100), Java 8 based for each loop has the best performance. With Map size is greater than 10000 elements, simple for each loop seems to be faster than other approaches. Please execute your own bench marking before taking a call for your implementation. Please keep in mind that best approach and efficiency is based on your requirement.

 

Summary

In this short post, we saw how to how to Iterate through a Map in Java. We saw how to do this using Java 8 and prior version of Java.There are multiple ways to iterate through the HashMap in Java and the best option dependents upon your requirement. If you are only interested in getting the keys from the map, I will go with keySet() as it is more efficient, similarly for the value only requirement, we should go with getValue() method. Make sure you choose the right method based on your requirements. All the code of this article is available Over on Github. This is a Maven-based project.

Subscribe
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments