Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging map and modifying value

There are two maps and I am trying to merge them into a single map (finalResp).

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

HashMap<String, String> finalResp = new HashMap<String, String>();

Solution - pre Java 8 - achieved like below:

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);
    }
}

Using Java 8, I am stuck at this:

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

How can I check if a map 2 key is not present in map 1 and modify the values?

like image 322
Umar Avatar asked Sep 26 '22 12:09

Umar


1 Answers

One possible way is to filter the unwanted elements (not contained in map2) and collect the result into a new 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()))
                            ));

Another way would be to create a copy of map2, retain all the keys of this Map that are also contained in map1 keys and finally replace all the values by applying the function changetoAnother.

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

Note that the advantage of the first solution is that it can be easily generalized to work for any two Maps:

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()))
                          ));
}

with

Map<String, String> finalResp = merge(map1, map2, (v1, v2) -> changetoAnother(v1, v2));
like image 63
Tunaki Avatar answered Sep 29 '22 08:09

Tunaki