diff --git a/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java b/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java index 4bf7b6ba5a..5138d44feb 100644 --- a/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java +++ b/core-java-collections/src/main/java/com/baeldung/map/java_8/MergeMaps.java @@ -28,6 +28,24 @@ public class MergeMaps { streamOf(); streamEx(); + + streamMerge(); + } + + private static void streamMerge() { + + Map map3 = map2.entrySet() + .stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (v1, v2) -> new Employee(v1.getId(), v2.getName()), + () -> new HashMap<>(map1) + ) + ); + + System.out.println(map3); } private static void streamEx() { @@ -55,9 +73,9 @@ public class MergeMaps { private static void streamConcat() { Map result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (value1, value2) -> new Employee(value1.getId(), value2.getName()) + Map.Entry::getKey, + Map.Entry::getValue, + (value1, value2) -> new Employee(value1.getId(), value2.getName()) )); result.entrySet().forEach(System.out::println); @@ -68,14 +86,13 @@ public class MergeMaps { map2.forEach( (key, value) -> map3.merge(key, value, (v1, v2) -> - new Employee(v1.getId(),v2.getName())) + new Employee(v1.getId(), v2.getName())) ); map3.entrySet().forEach(System.out::println); } - private static void initialize() { Employee employee1 = new Employee(1L, "Henry"); map1.put(employee1.getName(), employee1);