要映射的地图流

Dar*_*arz 12 java lambda java-8 java-stream

我怎么能展平StreamMap(同类型)s到一个Map用Java 8?

Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
    return stream. ???
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 20

我的语法可能有点偏,但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
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用方法引用:`Collectors.toMap(Map.Entry :: getKey,Map.Entry :: getValue)`(或者如果导入嵌套类:`Collectors.toMap(Entry :: getKey,Entry :: getValue) `) (7认同)
  • 请注意,如果同一个键出现多次,则2参数`toMap(...)`将抛出异常.如果那不是您想要的,请使用3参数`toMap(...)`.使用`(a,b) - > b`作为第三个参数来模拟`Map :: addAll`(后来的值会覆盖以前的值). (6认同)