有两张 map ,我正在尝试将它们合并为一张 map (finalResp
)。
Map<String, String[]> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
HashMap<String, String> finalResp = new HashMap<String, String>();
解决方案 - Java 8 之前 - 实现如下:
for (Map.Entry<String, String[]> entry : map1.entrySet()) {
if (map2.containsKey(entry.getKey())) {
String newValue = changetoAnother(map1.get(entry.getKey()), map2.get(entry.getKey()));
finalResp.put(entry.getKey(), newValue);
}
}
使用 Java 8,我被困在了这里:
HashMap<String, String> map3 = new HashMap<>(map2);
map1.forEach((k, v) -> map3.merge(k, v, (i, j) -> mergeValue(i, j) ));
如何检查映射 2 键是否不存在于映射 1 中并修改值?
最佳答案
一种可能的方法是过滤不需要的元素(不包含在 map2
中)并将结果收集到一个新的 Map 中:
Map<String, String> finalResp =
map1.entrySet().stream().filter(e -> map2.containsKey(e.getKey()))
.collect(Collectors.toMap(
Entry::getKey,
e -> changetoAnother(e.getValue(), map2.get(e.getKey()))
));
另一种方法是创建 map2
的副本,保留此 Map
的所有键,这些键也包含在 map1
键中,并且最后通过应用函数 changetoAnother
替换所有值。
Map<String, String> result = new HashMap<>(map2);
result.keySet().retainAll(map1.keySet());
result.replaceAll((k, v) -> changetoAnother(map1.get(k), v));
请注意,第一种解决方案的优点是它可以很容易地推广到适用于任何两个 map :
private <K, V, V1, V2> Map<K, V> merge(Map<K, V1> map1, Map<K, V2> map2, BiFunction<V1, V2, V> mergeFunction) {
return map1.entrySet().stream()
.filter(e -> map2.containsKey(e.getKey()))
.collect(Collectors.toMap(
Entry::getKey,
e -> mergeFunction.apply(e.getValue(), map2.get(e.getKey()))
));
}
与
Map<String, String> finalResp = merge(map1, map2, (v1, v2) -> changetoAnother(v1, v2));
关于java - 合并映射和修改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086143/