Anybody knows how to merge with Java 8 two maps of this type?
Map<String,  List<String>> map1--->["a",{1,2,3}]
Map<String,  List<String>> map2--->["a",{4,5,6}]
And obtain as result of the merge
Map<String,  List<String>> map3--->["a",{1,2,3,4,5,6}]
I´m looking for a non verbose way if exist. I know how to do it in the old fashion way.
Regards.
The general idea is the same as in this post. You create a new map from the first map, iterate over the second map and merge each key with the first map thanks to merge(key, value, remappingFunction). In case of conflict, the remapping function is applied: in this case, it takes the two lists and merges them; if there is no conflict, the entry with the given key and value is put.
Map<String, List<String>> mx = new HashMap<>(map1);
map2.forEach((k, v) -> mx.merge(k, v, (l1, l2) -> {
    List<String> l = new ArrayList<>(l1);
    l.addAll(l2);
    return l;
}));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With