合并 Java 中的两个映射值,如果键相同,则附加 Java 7 或 Java 8 中未覆盖的值

merge two Map Values in Java and if key is same append the Values not overwrite in Java 7 or Java 8

我想合并 2 Map,但是当键相同时,值应该附加而不是覆盖。

假设

Map<String, Set<String>> map1 = new HashMap<>();
Set<String> set1 = new HashSet<>();
set1.add("AB");
set1.add("BC");
map1.put("ABCD",set1);

Map<String, Set<String>> map2 = new HashMap<>();
Set<String> set2 =new HashSet<>();
set2.add("CD");
set2.add("EF");
map2.put("ABCD",set2);

map1.putAll(map2);

所以这里的键是 same.I 知道如果键相同,putAll 将覆盖值

但我正在寻找像

这样的输出
{ABCD=[AB,BC,CD,ED]}

如果有人能帮我解决,将不胜感激。

您可以使用 Stream API 合并相同键的值,检查 map2 是否具有来自 [=14= 的相同键] 并遍历它们并使用 addAll()

将值合并在一起
map1.entrySet().stream().filter(entry -> map2.containsKey(entry.getKey()))
                .forEach(entry -> entry.getValue().addAll(map2.get(entry.getKey())));

main 函数

public static void main(String[] args) {
    Map<String, Set<String>> map1 = new HashMap<>();
    Set<String> set1 = new HashSet<>();
    set1.add("AB");
    set1.add("BC");
    map1.put("ABCD", set1);

    Map<String, Set<String>> map2 = new HashMap<>();
    Set<String> set2 = new HashSet<>();
    set2.add("CD");
    set2.add("EF");
    map2.put("ABCD", set2);

    map1.entrySet()
        .stream()
        .filter(entry -> map2.containsKey(entry.getKey()))
        .forEach(entry -> entry.getValue().addAll(map2.get(entry.getKey())));

    System.out.println(map1);
}

output

{ABCD=[AB, BC, CD, EF]}

您可以使用 Stream.concat 连接两个映射,然后使用 groupingBy 映射键和值作为集合进行收集。

Map<String, Set<String>> res = 
       Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
             .collect(Collectors.groupingBy(e-> e.getKey(),
                                Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toSet())));

注:解决方案使用Java9+flatMapping

您可以使用地图的merge功能。这里将map2数据合并成map1

map2.forEach((key, val) -> map1.merge(key, val, (a, b) -> {a.addAll(b); return a;}));

输出:{ABCD=[AB, BC, CD, EF]}

您使用了提供给Collectors.toMap that specifies what to do with values of duplicate keys with Streams. Demo

的合并功能
final Map<String, Set<String>> map3 = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (a, b) -> Stream.concat(a.stream(), b.stream()).collect(Collectors.toSet())));

您可以使用类似的方法 Map#merge. Demo

final Map<String, Set<String>> map3 = new HashMap<>(map1);
map2.forEach((key, val) -> map3.merge(key, val,
        (a, b) -> Stream.concat(a.stream(), b.stream()).collect(Collectors.toSet())));