直接上代码
public static void mergeMap(){
Map<String, Set<String>> a = new HashMap();
a.put("A", new HashSet<>(Arrays.asList("1")));
Map<String, Set<String>> b = new HashMap();
b.put("A", new HashSet<>(Arrays.asList("1", "22")));
//方案一 先将两个集合合并成一个流再合并
Map<String, Set<String>> d = Stream.concat(a.entrySet().stream(), b.entrySet().stream()).collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(Set<String> oldList, Set<String> newList) ->{
oldList.addAll(newList);
return newList;
}));
System.out.println("d-->" + d);
//方案二 遍历a集合往b集合中合并
a.forEach((key, value) -> b.merge(key, value, (Set<String> oldList, Set<String> newList) ->{
oldList.addAll(newList);
return oldList;
}));
System.out.println("b-->" + b);
}
方案一注释:
Collectors.toMap(key, value, key重复该如何操作);
方案二注释:
merge(key, value, key重复该如何操作)