Java收集Set的Map

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

Java collect Map of Sets

问题

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Set<Map<String, Set<String>>> mapsSet = new HashSet<>();
        // Add your maps to the 'mapsSet' here

        Map<String, Set<String>> combinedMap = mapsSet.stream()
                .flatMap(map -> map.entrySet().stream())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (set1, set2) -> {
                            Set<String> combinedSet = new HashSet<>(set1);
                            combinedSet.addAll(set2);
                            return combinedSet;
                        }
                ));

        System.out.println(combinedMap);
    }
}

请注意,上面的代码示例中,我已经省略了输入部分的处理,你需要将你的地图添加到 mapsSet 集合中。在运行代码时,它将按照你的要求,将所有地图合并成一个地图,并对相同键的值集进行联合。最终结果将打印在控制台上。

如果你还有其他问题,欢迎随时问我。

英文:

I have a set of maps

Set&lt;Map&lt;String, Set&lt;String&gt;&gt;&gt;

I would like, using java streams, to combine all the maps in the set into one where the keys are all the keys of the maps and the values the union of the sets which are associated to the same key.

Output:

Ma&lt;String, Set&lt;String&gt;&gt;

Example input:

[
 {
  a: [1,2,3],
  b: [2,3,4]
 },
 {
  a: [4,5,6]
 }
]

Example output:

{
 a: [1,2,3,4,5,6]
 b: [2,3,4]
}

I tried some solution but so far not solved yet

答案1

得分: 2

你可以创建一个包含所有内部映射条目的流,并将它们收集到一个单独的映射中:

Map<String, Set<String>> output =
    input.stream()
         .flatMap(m -> m.entrySet().stream())
         .collect(Collectors.toMap(Map.Entry::getKey,
                                   Map.Entry::getValue,
                                   (v1, v2) -> {v1.addAll(v2); return v1;}));
英文:

You can create a Stream of all the entries of all the inner maps, and collect them to a single map:

Map&lt;String, Set&lt;String&gt;&gt; output =
    input.stream()
         .flatMap(m -&gt; m.entrySet().stream())
         .collect(Collectors.toMap(Map.Entry::getKey,
                                   Map.Entry::getValue,
                                   (v1,v2) -&gt; {v1.addAll(v2); return v1;}));

huangapple
  • 本文由 发表于 2020年10月27日 16:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64550674.html
匿名

发表评论

匿名网友

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

确定