要映射的地图流

2022-09-01 08:45:06

如何在Java 8中将s(相同类型)的a平展为单个?StreamMapMap

Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
    return stream. ???
}

答案 1

我的语法可能有点偏差,但flatMap应该为您完成大部分工作:

Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
    return stream.flatMap (map -> map.entrySet().stream()) // this would create a flattened
                                                           // Stream of all the map entries
                 .collect(Collectors.toMap(e -> e.getKey(),
                                           e -> e.getValue())); // this should collect
                                                               // them to a single map
}

答案 2

我想提出一个使用reduce()的解决方案,这对我来说更直观。不过,我会内联使用它。

Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
    return stream.reduce(new HashMap<>(), Util::reduceInto);
}

在Util中.java:

public static <R, T> Map<R, T> reduceInto(Map<R, T> into, Map<R, T> valuesToAdd) {
    reduceInto.putAll(valuesToAdd);
    return reduceInto;
}

在这种情况下,reduceInto() 适用于任何类型的映射,并使用可变性来避免为流的每个项目创建新的映射。

重要提示:尽管此方法允许在流中重复密钥,但 reduceInto() 不是关联的,这意味着如果您有重复的密钥,则无法保证哪个密钥将是最终值。


推荐