java8下map合并可以有以下几种方式:
map为待合并集合,map2为被合并集合(将map2中元素合并到map中)
- map.merge()
map2.forEach((key, value) -> { map.merge(key, value, (origin, newVlue) -> { origin.putAll(newVlue); return origin; }); });
- Stream.concat()
Stream .concat(map.entrySet().stream(), map2.entrySet().stream()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (origin, newValue) -> { origin.putAll(newValue); return origin; }));
- Stream.of()
Stream .of(map, map2) .flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (origin, newValue) -> { origin.putAll(newValue); return origin; }));
- Simple Streaming
map2.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (origin, newValue) -> { origin.putAll(newValue); return origin; }, () -> map // 汇总者 ));
参考:https://www.baeldung.com/java-merge-maps
源码:https://github.com/eugenp/tutorials/tree/master/java-collections-maps-2