Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explore the different ways to collect a stream of Map.Entry objects into a LinkedHashMap.

LinkedHashMap is similar to HashMap but differs in the respect that it maintains the insertion order. 

2. Understanding the Problem

We can obtain a stream of map entries by invoking the entrySet() method followed by the stream() method. This stream gives us the ability to process each entry.

Processing is achieved via intermediate operations and can involve filtering via the filter() method or transforming via the map() method. Ultimately, we must decide what we want to do with our stream via an appropriate terminal operation. In our case, we face the challenge of collecting the stream into a LinkedHashMap.

Let’s suppose we have the following map for this tutorial:

Map<Integer, String> map = Map.of(1, "value 1", 2, "value 2");

We’ll stream and collect the map entries into a LinkedHashMap and aim to satisfy the following assertion:

assertThat(result) 
  .isExactlyInstanceOf(LinkedHashMap.class) 
  .containsOnly(entry(1, "value 1"), entry(2, "value 2"));

3. Using the Collectors.toMap() Method

We can use an overload of the Collectors.toMap() method to collect our stream into a map of our choosing:

static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, 
        BinaryOperator<U> mergeFunction, Supplier<M> mapFactory)

Therefore, we use this collector as part of the terminal collect() operation for our stream:

map
  .entrySet()
  .stream()
  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> {throw new RuntimeException();}, LinkedHashMap::new));

To retain each entries’ key-value pair, we use the method references Map.Entry::getKey and Map.Entry::getValue for the keyMapper and valueMapper functions. The mergeFunction allows us to deal with any conflicts for entries that have the same key. Thus, we throw a RuntimeException as there shouldn’t be any conflicts for our use case. Finally, we use the LinkedHashMap constructor reference for the mapFactory to supply the map for which the entries will be collected into.

We should note that it’s possible to use the other toMap() overloads to achieve our goal. However, the mapFactory parameter is absent for these methods, so the stream is collected into a HashMap under the hood. Therefore, we can use LinkedHashMap‘s constructor to convert the HashMap to our desired type:

new LinkedHashMap<>(map
  .entrySet()
  .stream()
  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

However, since this creates two map instances to achieve our goal, the initial approach is preferred. 

4. Using the Collectors.groupingBy() Method

We can use an overload of the Collectors.groupingBy() method to specify the map into which the grouping collects:

static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> 
    groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, 
        Collector<? super T, A, D> downstream)

Let’s say we have an existing map of city-to-country entries:

Map<String, String> cityToCountry = Map.of("Paris", "France", "Nice", "France", "Madrid", "Spain");

However, we want to group the cities by country. Thus, we use the groupingBy() with the collect() method:

Map<String, Set<String>> countryToCities = cityToCountry
  .entrySet()
  .stream()
  .collect(Collectors.groupingBy(Map.Entry::getValue, LinkedHashMap::new, Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));

assertThat(countryToCities)
  .isExactlyInstanceOf(LinkedHashMap.class)
  .containsOnly(entry("France", Set.of("Paris", "Nice")), entry("Spain", Set.of("Madrid")));

We use the Map.Entry::getValue method reference as the classifier function to group by the country. We state the desired map to collect the grouping into by using LinkedHashMap::new for the mapFactory. Finally, we utilize the Collectors.mapping() method as the downstream collector to extract the keys from our entries to collect into each set.

5. Using the put() Method

We can collect our stream into an existing LinkedHashMap using the terminal forEach() operation with the put() method:

Map<Integer, String> result = new LinkedHashMap<>();

map
  .entrySet()
  .stream()
  .forEach(entry -> result.put(entry.getKey(), entry.getValue()));

Alternatively, we could avoid streaming altogether and use the forEach() available for the Set object:

map
  .entrySet()
  .forEach(entry -> result.put(entry.getKey(), entry.getValue()));

To further simplify, we could use the forEach() on the map directly:

map.forEach((k, v) -> result.put(k, v));

However, we should note that each of these introduces side-effect operations into our functional programming by modifying the existing map. Therefore, it would be more appropriate to use a more imperative style:

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    result.put(entry.getKey(), entry.getValue());
}

We use an enhanced for loop to iterate and add the key-value from each entry to the existing LinkedHashMap.

6. Using LinkedHashMap‘s Constructor

If we want to simply convert a map into a LinkedHashMap, it’s not a requirement to stream the entries to do this. We can simply convert the map using LinkedHashMap‘s constructor:

new LinkedHashMap<>(map);

7. Conclusion

In this article, we’ve explored various ways to collect a stream of map entries into a LinkedHashMap. We explored the use of different terminal operations and alternatives to streaming to achieve our goal.

As always, the code samples used 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 open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.