Stream of maps to map

こ雲淡風輕ζ 提交于 2020-06-22 11:11:36

问题


How can I flatten a Stream of Maps (of the same types) to a single Map in Java 8?

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

回答1:


My syntax may be a bit off, but flatMap should do most of the work for you :

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
}


来源:https://stackoverflow.com/questions/26752919/stream-of-maps-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!