今天有一个场景,需要将两个Map合并,示例数据如下:
# Map1
{
"1000":[
"101",
"102",
"103"
],
"1001":[
"201",
"202"
]
}
# Map2
{
"1000":[
"102",
"103",
"104"
],
"1002":[
"301",
"302"
]
}
# 合并后的结果
{
"1000":[
"101",
"102",
"103",
"104"
],
"1001":[
"201",
"202"
],
"1002":[
"301",
"302"
]
}
如果硬写的话还是比较麻烦,但是使用Stream流可以很方便的完成这个操作
Map<String, Set<String>> oldData = JSON.parseObject("{\"1000\":[101,102,103],\"1001\":[201,202]}", new TypeReference<Map<String, Set<String>>>() {
});
Map<String, Set<String>> newData = JSON.parseObject("{\"1000\":[102,103,104],\"1002\":[301,302]}", new TypeReference<Map<String, Set<String>>>() {
});
Map<String, Set<String>> finalMap = Stream.of(oldData, newData)
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(set1, set2) -> {
Set<String> mergeSet = new HashSet<>(set1);
mergeSet.addAll(set2);
return mergeSet;
}
)
);
;
需要特别说明的是 Collectors.toMap( )中的第三个参数是Key相同情况下的处理规则,上图的代码意思就是如果这两个Map的Key相同,则把两个Key对应的Value放入同一个Set中返回