在Java8中,如何将(相同类型的)Map
的Stream
展平为单个Map
?
Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
return stream. ???
}
发布于 2014-11-05 08:53:50
我的语法可能有点错,但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
}
发布于 2020-09-09 04:31:00
我想提出一个使用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() 不是 associative,这意味着如果有重复的键,就不能保证哪一个是最终的值。
https://stackoverflow.com/questions/26752919
复制相似问题