合并两个地图以获取Map <string,set <information =“”>&gt;

时间:2017-01-07 10:38:23

标签: java collections

如何合并2个地图以获取将地图映射到集合的新地图。 例如:

Map<String, Information> map1;
Map<String, Information> map2;

现在我想把结果作为

Map<String, Set<Information>> resultMap;

5 个答案:

答案 0 :(得分:3)

使用流:

Map<String, Information> map1;
Map<String, Information> map2;

Map<String, Set<Information>> result = Stream.of(map1, map2)
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Entry::getKey,
        Collectors.mapping(Entry::getValue, Collectors.toSet())));

答案 1 :(得分:0)

这样就可以了:

        Map<String, Information> map1;
        Map<String, Information> map2;

        Map<String, Set<Information>> resultMap = new HashMap<>();

        Set<String> keySet = new HashSet<>(map1.keySet());
        keySet.addAll(map2.keySet());

        keySet.stream()
                .forEach(t -> {
                    Set<Information> data = new HashSet<>();
                    if (map1.get(t) != null)  {
                        data.add(map1.get(t));
                    }
                    if (map2.get(t) != null)  {
                        data.add(map2.get(t));
                    }

                    resultMap.put(t, data);
                });

请注意,只有在Information班级overriden等于方法

时才会按照您的方式运作

答案 2 :(得分:0)

例如,您可以迭代2张原始地图(map1.keySet()然后map2.keySet())的关键字来填充Map<String, Set<Information>> resultMap = new HashSet<String, Set<Information>>的新实例。

每次添加值时,如果尚未添加任何值,请将其添加到现有的Set或全新的。

Optional<Set<Information>> data = Optional.of(resultMap.get(aKey1));
if (data.isPresent()) {
    data.get().add(map1.get(aKey1))
} else {
    final Set<Information> newSet = new HashSet<>();
    newSet.add(map1.get(aKey1));
    resultMap.put(aKey1, newSet);
}

您还可以使用Streams尝试更实用的方法。

答案 3 :(得分:0)

@Jom已经使用stream给出了一个非常好的答案。
这只是使用流和地图的merge功能的另一个答案。

Map<String, Set<String>> resultMap = new HashMap<>();

Stream.of(map1, map2).flatMap(map -> map.entrySet().stream()).forEach(entry -> {
    resultMap.merge(entry.getKey(), Collections.singleton(entry.getValue()),
            (v1, v2) -> Stream.concat(v1.stream(), v2.stream()).collect(Collectors.toSet()));
});

答案 4 :(得分:-1)

试试这个

private Map<String, Set<Information>> mergeMap(Map<String, Information> map1, Map<String, Information> map2) {
    Map<String, Set<Information>> resultMap = new HashMap<>();
    for (String key : map1.keySet()) {
        Set<Information> set;
        if(resultMap.containsKey(key))
            set = resultMap.get(key);
        else 
            set = new HashSet<>();
        set.add(map1.get(key));
        resultMap.put(key, set);
    }

    for (String key : map2.keySet()) {
        Set<Information> set;
        if(resultMap.containsKey(key))
            set = resultMap.get(key);
        else
            set = new HashSet<>();
        set.add(map2.get(key));
        resultMap.put(key, set);
    }

    return resultMap;
}