问题
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:
Does this also happen with version 1?
Which one should I select for fastest and accurate processing?
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 withstream.map(..)
.
来源:https://stackoverflow.com/questions/61479650/stream-map-with-collectors-tomap-vs-accumulator