Collect Stream of entrySet() to a LinkedHashMap – 将 entrySet() 的数据流收集到 LinkedHashMap 中

最后修改: 2024年 2月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

在本教程中,我们将探讨将 Map.Entry 对象流收集到 LinkedHashMap 中的不同方法。

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

A LinkedHashMapHashMap类似,但在保持插入顺序方面有所不同。

2. Understanding the Problem

2.了解问题

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.

我们可以通过调用 entrySet() 方法,然后再调用 stream() 方法,获得地图条目的流。该流使我们能够处理每个条目。

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.

处理是通过中间操作实现的,可能涉及通过 filter() 方法进行过滤,或通过 map() 方法进行转换。最终,我们必须通过适当的终端操作来决定要对流做什么。在我们的例子中,我们面临的挑战是将流收集到 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:

我们将把地图条目分流并收集到一个 LinkedHashMap 中,目标是满足以下断言:

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

3. Using the Collectors.toMap() Method

3.使用 Collectors.toMap() 方法

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

我们可以使用 Collectors.toMap() 方法的重载,将数据流收集到我们选择的映射中:

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:

因此,我们将该收集器用作流的终端 collect() 操作的一部分:

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.

为了保留每个条目的键值对,我们在 keyMappervalueMapper 函数中使用了方法引用 Map.Entry::getKeyMap.Entry::getValue mergeFunction 允许我们处理具有相同键的条目的任何冲突。因此,我们会抛出一个 RuntimeException 异常,因为在我们的用例中不应该存在任何冲突。最后,我们使用mapFactoryLinkedHashMap构造函数引用来提供将条目收集到其中的映射。

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:

我们应该注意到,使用其他 toMap() 重载也可以实现我们的目标。但是,这些方法中没有 mapFactory 参数,因此数据流会被收集到 HashMap 中。因此,我们可以使用 LinkedHashMap 的构造函数将 HashMap 转换为我们所需的类型:

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

4.使用 Collectors.groupingBy() 方法

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

我们可以使用 Collectors.groupingBy() 方法的重载来指定分组收集的地图:

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:

但是,我们希望按国家对城市进行分组。因此,我们使用 groupingBy()collect() 方法:

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.

我们使用 Map.Entry::getValue 方法引用作为 classifier 函数来按国家分组。我们使用 LinkedHashMap::new 作为 mapFactory 来说明所需的地图,以便将分组收集到其中。最后,我们使用 Collectors.mapping() 方法作为 下游收集器,从条目中提取键值,将其收集到每个组中。

5. Using the put() Method

5.使用 put() 方法

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

我们可以使用终端 forEach() 操作和 put() 方法,将数据流收集到现有的 LinkedHashMap 中:

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:

或者,我们可以完全避免流式处理,而使用 Set 对象可用的 forEach() 方法:

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

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

为了进一步简化,我们可以直接在地图上使用 forEach()

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:

然而,我们应该注意到,通过修改现有的 map,这些操作都在函数式编程中引入了副作用操作。因此,使用命令式风格更为合适:

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.

我们使用增强的 for 循环来遍历并将每个条目的键值添加到现有的 LinkedHashMap 中。

6. Using LinkedHashMap‘s Constructor

6.使用 LinkedHashMap 的构造函数

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:

如果我们想简单地将地图转换为 LinkedHashMap,则不需要对条目进行流式处理。我们可以使用 LinkedHashMap 的构造函数简单地转换地图:

new LinkedHashMap<>(map);

7. Conclusion

7.结论

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.

在本文中,我们探索了将地图条目流收集到 LinkedHashMap 中的各种方法。我们探索了使用不同的终端操作和流的替代方法来实现我们的目标。

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

一如既往,本文中使用的代码示例可在 GitHub 上找到