Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, 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 these are all sets, similar iteration principles apply to all of them.

The Map.entrySet 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 closer look at a few of these.

Further reading:

Guide to the Java 8 forEach

A quick and practical guide to Java 8 forEach

How to Iterate Over a Stream With Indices

Learn several ways of iterating over Java 8 Streams using indices

Finding the Highest Value in a Java Map

Take a look at ways to find the maximum value in a Java Map structure.

2. EntrySet and for Loop

First, let's see how to iterate through a Map using the EntrySet:

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 is 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

Now let's 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 just 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, we 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 article, we focused on a simple but critical operation, iterating through the entries of a map.

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

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

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!