package modern.challenge; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public final class Maps { private Maps() { throw new AssertionError("Cannot be instantiated"); } public static Map mergeMapsV1(Map map1, Map map2) { if (map1 == null || map2 == null) { throw new IllegalArgumentException("None of the maps can be null"); } Map map = new HashMap<>(map1); map2.forEach( (key, value) -> map.merge(key, value, (v1, v2) -> v2)); return map; } public static Map mergeMapsV2(Map map1, Map map2) { if (map1 == null || map2 == null) { throw new IllegalArgumentException("None of the maps can be null"); } Stream> combined = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()); Map map = combined.collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2)); return map; } }