合并地图和修改值

Uma*_*mar 5 java collections lambda java-8 java-stream

有两个地图,我试图将它们合并到一个地图(finalResp).

Map<String, String[]> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();

HashMap<String, String> finalResp = new HashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

解决方案 - 在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Java 8,我坚持这样:

HashMap<String, String> map3 = new HashMap<>(map2);
map1.forEach((k, v) -> map3.merge(k, v, (i, j) -> mergeValue(i, j) ));
Run Code Online (Sandbox Code Playgroud)

如何检查地图1中是否没有地图2键并修改值?

Tun*_*aki 4

一种可能的方法是过滤不需要的元素(不包含在 中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()))
                            ));
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建 的副本,保留也包含在键中map2的所有键,最后通过应用该函数替换所有值。Mapmap1changetoAnother

Map<String, String> result = new HashMap<>(map2);
result.keySet().retainAll(map1.keySet());
result.replaceAll((k, v) -> changetoAnother(map1.get(k), v));
Run Code Online (Sandbox Code Playgroud)

请注意,第一个解决方案的优点是它可以轻松推广到适用于任意两个 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()))
                          ));
}
Run Code Online (Sandbox Code Playgroud)

Map<String, String> finalResp = merge(map1, map2, (v1, v2) -> changetoAnother(v1, v2));
Run Code Online (Sandbox Code Playgroud)