1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package org.acme;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class MergeTest {
@Test
public void testMerge() {
Map<String, List<String>> mapGlobal = new HashMap<String, List<String>>();
Map<String, List<String>> mapAdded = new HashMap<String, List<String>>();
mapGlobal.put("a", Arrays.asList("1", "3", "5", "7"));
mapAdded.put("b", Arrays.asList("10", "30", "50", "70"));
mapAdded.put("a", Arrays.asList("1", "9", "15"));
Map<String, List<String>> other =
Stream.of(mapGlobal, mapAdded)
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue,
(t,u) -> Stream.of(t, u).flatMap(List::stream).distinct().collect(Collectors.toList())
)
);
System.out.println(other);
}
} |
Partager