Map merge and change value

There are two cards, and I'm trying to combine them into one card ( finalResp ).

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

The solution - pre Java 8 - is achieved as shown 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 with this:

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

How to check if the card 2 key is on card 1 and change the values?

+5
source share
1 answer

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)); 
+4
source

Source: https://habr.com/ru/post/1233537/


All Articles