Iterating over maps in Java

       A Map is a popular Java collection that is used to store key/value pairs. In many situations we are going to need to iterate over the map to display its contents or do some manipulations.

One way to iterate over a map is by using the Map.entrySet() method, which returns a collection-view of the map.

The latter collection elements are of Map.Entry class, we are able to get key and value using getKey() and getValue() methods.

The only way to obtain a reference to a map entry is from the iterator of this collection-view.

       In this post we are going to go over 3 ways to iterate over the map entry using iterator, for loop and lambda expressions.

First let us create a map and give it keys for months of the year with values of how many days are in this month.

        Map<String, String> months = new LinkedHashMap<String, String>();
        months.put(“January”, “31 days”);
        months.put(“February”, “28 days in a common year and 29 days in leap years”);
        months.put(“March”, “31 days”);
        months.put(“April”, “30 days”);
        months.put(“May”, “31 days”);
        months.put(“June”, “30 days”);
        months.put(“July”, “31 days”);
        months.put(“August”, “31 days”);
        months.put(“September”, “30 days”);
        months.put(“October”, “31 days”);
        months.put(“November”, “30 days”);
        months.put(“December”, “31 days”);

1- Iterator

By using the Iterator() API we iterate over the map entry set.

        for (Map.Entry<String, String> entry : months.entrySet()) {
            System.out.println(entry.getKey() + “:” + entry.getValue());
        }

2- For loop

Next we iterate the map entry set using the classical for each method.

        Iterator<Map.Entry<String, String>> iterator = months.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry.getKey() + “:” + entry.getValue());
        }

3- Lambda expression

Lambda expressions were introduced in Java 8, this is the simplest way until now as we do not need to convert a map into a set of entries.

        months.forEach((k, v) -> System.out.println((k + “:” + v)));