One possible way is to filter out unwanted elements (not contained in map2 ) and collect the result in 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 is to create a copy of map2 , save all the keys of this Map , which are also contained in the map1 keys, and finally replace all the values ββusing the changetoAnother function.
Map<String, String> result = new HashMap<>(map2); result.keySet().retainAll(map1.keySet()); result.replaceAll((k, v) -> changetoAnother(map1.get(k), v));
Please note that the advantage of the first solution is that it can be easily generalized to work for any two cards:
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));