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

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

How to transform a list of maps to map

问题

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

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

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

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

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

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

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

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

英文:

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

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

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

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

This is my solution - with enhancement for loop.

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

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

Note: Keys are unique - no duplicates.

答案1

得分: 4

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

  1. Map<Long, Long> newMap =
  2. listMap.stream()
  3. .flatMap(m -> m.entrySet().stream())
  4. .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

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

答案2

得分: 3

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

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

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

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

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

  1. Map&lt;Long, Long&gt; newMap = listMap.stream()
  2. .flatMap(map -&gt; map.entrySet().stream())
  3. .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

  1. 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:

确定