Iterate over a Map in Java

1. Overview

In this quick article, we’ll have a look at the different ways of iterating through the entries of a Map in Java.

Simply put, we can extract the contents of a Map using keySet(), valueSet() or entrySet(). Since those are all sets, similar iteration principles apply to all of them.

The Map.entrySet[.s1]# API returns a collection-view of the map, whose elements are from the Map class. The only way to obtain a reference to a single map entry is from the iterator of this collection view. #

The entry.getKey() returns the key and entry.getValue() returns the corresponding value.

Let’s have a look at a few of these.

2. EntrySet and For Loop

First, let’s see how to iterate through a Map using the Entry*Set*:

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

Here, we’re converting our map to a set of entries and then iterating through them using the classical for-each approach.

We can access a key of each entry by calling getKey() and we can access a value of each entry by calling getValue().

 

3. Iterator and EntrySet

Another approach would be to obtain a set of entries and perform the iteration using an Iterator:

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

Notice how we can get the Iterator instance using the iterator() API of entrySet(). Then, as usual, we loop through the iterator with iterator.next().

4. With Lambdas

Let’s now see how to iterate a Map using lambda expressions.

Like most other things in Java 8, this turns out to be much simpler than the alternatives; we’ll make use of the forEach() method:

public void iterateUsingLambda(Map<String, Integer> map) {
    map.forEach((k, v) -> System.out.println((k + ":" + v)));
}

In this case, we do not need to convert a map to a set of entries. To learn more about lambda expressions, you can start here.

5. Stream API

Stream API is one of the main features of Java 8. We can use this feature to loop through a Map as well but as in previous examples, we need to obtain a set of entries first:

public void iterateUsingStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream()
      // ...
      .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}

This should be used when we are planning on doing some additional Stream processing. Otherwise, it’s just a simple forEach() as described previously.

To learn more about Stream API, check out this article.

6. Conclusion

In this tutorial, we’ve focused on a simple but critical operation – iterating through the entries of a map.

We’ve seen a couple of methods which can be used with Java 8 only, namely Lambda expressions and the Stream API.

As always, the code examples in the article can be found over on GitHub.

Leave a Reply

Your email address will not be published.