Merge Two List Value Cards

Does anyone know how to merge with Java 8 with two cards of this type?

Map<String,  List<String>> map1--->["a",{1,2,3}]
Map<String,  List<String>> map2--->["a",{4,5,6}]

And get as a result of the merger

Map<String,  List<String>> map3--->["a",{1,2,3,4,5,6}]

I am looking for an unnecessary way if it exists. I know how to do it the old way.

Sincerely.

+4
source share
3 answers

The general idea is the same as in this post . You create a new card from the first card, iterate over the second card and combine each key with the first card thanks merge(key, value, remappingFunction). In case of conflict, the reassignment function is applied: in this case, it takes two lists and combines them; if there is no conflict, an entry is entered with the specified key and value.

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

, , :

Map<K,List<V>> result = Stream.of(map1,map2) // Stream<Map<K,List<V>>>
    .flatMap(m -> m.entrySet().stream()) // Stream<Map.Entry<K,List<V>>>
    .flatMap(e -> e.getValue().stream() // Inner Stream<V>...
            .map(v -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(), v))) 
    // ...flatmapped into an outer Stream<Map.Entry<K,V>>>
    .collect(Collectors.groupingBy(e -> e.getKey(), Collectors.mapping(e -> e.getValue(), Collectors.toList())));

, Collectors.reducing() By, . ,

+1

You need to use Install instead of List and do it like this:

Map<String, Set<String>> map1--->["a",{1,2,3}]
Map<String, Set<String>> map2--->["a",{4,5,6}]

map1.forEach((k, v) -> v.addAll(map2.get(k) == null : new HashSet<> ? map2.get(k)));
+1
source

All Articles