Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two List value maps

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.

like image 667
paul Avatar asked Feb 07 '23 15:02

paul


1 Answers

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;
}));
like image 61
Tunaki Avatar answered Feb 13 '23 23:02

Tunaki