Map merged = lists.stream()
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// 不想覆盖,保留最初的值:
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a));
// 覆盖key相同的值,
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
一种更简单的方式用StreamEx,一个第三方开源库:
// 没有MergeFunction,如果在不同的Map有相同的Key会报错:
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap();
// 保留最初的值
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap((a, b) -> a);
// 覆盖最初的值,用最后的值
StreamEx.of(lists).flatMapToEntry(Function.identity()).toMap((a, b) -> b);
1, 对的,如果Map里有Null值会出错的,更多的原因可以参阅:java-8-nullpointerexception-in-collectors-tomap。 你可以把Null值filter掉,或者用forEach + putAll,如果Null值是你需要保留的:
lists.stream().flatMap(m -> m.entrySet().stream()).filter(e -> e.getValue() != null)...
//或者:
StreamEx.of(lists).flatMapToEntry(Function.identity()).nonNullValues()...