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