stream map with Collectors.toMap vs Accumulator

隐身守侯 提交于 2020-05-14 14:18:51

问题


I have a a set of enums Set<Task> tasks; and process this to an EnumMap:

Version 1 (using supplier, accumulator, combiner):

return task.stream()
           .collect(() -> new EnumMap<>(Task.class),
                        (map, item) -> map.put(item, compute(item)), 
                        Map::putAll);

Version 2 (using Collectors.toMap):

return tasks.stream().collect(
       Collectors.toMap(
              Function.identity(), 
              t -> compute(t), 
              null, 
              () -> new EnumMap<>(Task.class)));

I like version 1 more because it is shorter. However, I must select the fastest version. Will version 1 work good with parallelStream? Unlike version 2 which uses Collectors.toMap has the following API-note:

Impl Note: For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation.

3 Questions:

  1. Does this also happen with version 1?

  2. Which one should I select for fastest and accurate processing?

  3. And is there a way to eliminate the need for materializing it into an EnumMap? I was thinking about returning only a key-value-stream, but it seems not possible with stream.map(..).

来源:https://stackoverflow.com/questions/61479650/stream-map-with-collectors-tomap-vs-accumulator

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