如何将一组地图的列表转换为地图

huangapple go评论78阅读模式
英文:

How to transform a list of maps to map

问题

我有一个映射列表(Map<Long, Long>)

List<Map<Long, Long>> listMap = List.of(
        Map.of(10L, 11L),
        Map.of(20L, 21L),
        Map.of(30L, 31L));

我想将它转换为一个映射(Map<Long, Long>)

Map<Long, Long> newMap = Map.of(
        10L, 11L,
        20L, 21L,
        30L, 31L);

这是我的解决方案 - 使用增强型循环。

Map<Long, Long> newMap = new HashMap<>();
for (Map<Long, Long> map : listMap) {
    Long key = (Long) map.keySet().toArray()[0];
    newMap.put(key, map.get(key));
}

是否有更好的方法?我可以使用Java流来进行这个转换吗?

注:键是唯一的 - 没有重复项。

英文:

I have a list of maps (Map<Long, Long>)

List&lt;Map&lt;Long, Long&gt;&gt; listMap = List.of(
        Map.of(10L, 11L),
        Map.of(20L, 21L),
        Map.of(30L, 31L));

And I want to transform it into a Map<Long, Long>

Map&lt;Long, Long&gt; newMap = Map.of(
        10L, 11L,
        20L, 21L,
        30L, 31L);

This is my solution - with enhancement for loop.

Map&lt;Long, Long&gt; newMap = new HashMap&lt;&gt;();
for (Map&lt;Long, Long&gt; map : listMap) {
    Long key = (Long) map.keySet().toArray()[0];
    newMap.put(key, map.get(key));
}

Is there a better approach? Can I use Java streams for this transformation?

Note: Keys are unique - no duplicates.

答案1

得分: 4

你可以使用flatMap来展平每个映射的条目列表,并使用Collectors.toMap将其收集为一个映射:

Map<Long, Long> newMap = 
    listMap.stream()
           .flatMap(m -> m.entrySet().stream())
           .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
英文:

You can flatMap to flatten every map's entry of list and collect as a map using Collectors.toMap

Map&lt;Long, Long&gt; newMap = 
    listMap.stream()
           .flatMap(m -&gt; m.entrySet().stream())
           .collect(Collectors.toMap(e -&gt; e.getKey(), e -&gt; e.getValue()));

答案2

得分: 3

足够简单。获取基础映射的所有条目流,然后使用 Collectors.toMap 进行收集:

Map<Long, Long> newMap = listMap.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

如果存在重复的键,虽然你说不会有这种情况,但会抛出异常:

java.lang.IllegalStateException: Duplicate key <thekey>
英文:

Simple enough. Get a stream of all the entries of the underlying maps, and collect with Collectors.toMap

Map&lt;Long, Long&gt; newMap = listMap.stream()
    .flatMap(map -&gt; map.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

If there is a duplicate key, which you said there will not be, it will throw

java.lang.IllegalStateException: Duplicate key &lt;thekey&gt;

huangapple
  • 本文由 发表于 2020年9月18日 19:17:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63954733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定