Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll 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 entrySet(), keySet(), or values(). Since these are all sets, similar iteration principles apply to all of them.

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. Short Introduction to Map‘s entrySet(), keySet(), and values() Methods

Before we iterate through a map using the three methods, let’s understand what these methods do:

  • entrySet() – returns a collection-view of the map, whose elements are from the Map.Entry class. The entry.getKey() method returns the key, and entry.getValue() returns the corresponding value
  • keySet() – returns all keys contained in this map as a Set
  • values() – returns all values contained in this map as a Set
Next, let’s see these methods in action.

3. Using a for Loop

3.1. Using entrySet()

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 extracting the Set of entries from our Map and then iterating through them using the classical for-each approach.

3.2. Using keySet()

Alternatively, we can first get all keys in our Map using the keySet method and then iterate through the map by each key:

public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
    for (String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key));
    }
}

3.3. Iterating Over Values Using values()

Sometimes, we’re only interested in the values in a map, no matter which keys are associated with them. In this case, values() is our best choice:

public void iterateValues(Map<String, Integer> map) {
    for (Integer value : map.values()) {
        System.out.println(value);
    }
}

4. Iterator

Another approach to perform the iteration is using an Iterator. Next, let’s see how the methods work with an Iterator object.

4.1. Iterator and entrySet()

First, let’s iterate over the map using an Iterator and entrySet():

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 the Set returned by entrySet(). Then, as usual, we loop through the Iterator with iterator.next().

4.2. Iterator and keySet()

Similarly, we can iterate through the Map using an Iterator and keySet():

public void iterateUsingIteratorAndKeySet(Map<String, Integer> map) {
    Iterator<String> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        System.out.println(key + ":" + map.get(key));
    }
}

4.3. Iterator and values()

We can also walk through the map’s values using an Iterator and the values() method:

public void iterateUsingIteratorAndValues(Map<String, Integer> map) {
    Iterator<Integer> iterator = map.values().iterator();
    while (iterator.hasNext()) {
        Integer value = iterator.next();
        System.out.println("value :" + value);
    }
}

5. Using Lambdas and Stream API

Since version 8, Java has introduced the Stream API and lambdas. Next, let’s see how to iterate a map using these techniques.

5.1. Using forEach() and Lambda

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 don’t need to convert a map to a set of entries. To learn more about lambda expressions, we can start here.

We can, of course, start from the keys to iterate over the map:

public void iterateByKeysUsingLambda(Map<String, Integer> map) {
    map.keySet().foreach(k -> System.out.println((k + ":" + map.get(k))));
}

Similarly, we can use the same technique with the values() method:

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

5.2. Using Stream API

Stream API is one significant feature of Java 8. We can use this feature to loop through a Map as well.

Stream API should be used when we’re planning on doing some additional Stream processing; otherwise, it’s just a simple forEach() as described previously.

Let’s take entrySet() as the example to see how Stream API works:

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

The usage of Stream API with the keySet() and values() methods would be pretty similar to the example above.

6. Conclusion

In this article, we focused on a critical but straightforward operation: iterating through the entries of a Map.

We explored a couple of methods that 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.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!