When you want to sum an integer value from a stream, there are two main ways of doing it:
ToIntFunction<...> mapFunc = ...
int sum = stream().collect(Collectors.summingInt(mapFunc))
int sum = stream().mapToInt(mapFunc).sum()
The first involves boxing the returned integer & unboxing it, but there's an extra step involved in the second.
Which is more efficient/clearer?
You are looking at the intersection of two otherwise distinct use cases. Using
mapToInt(…)
allows you to chain otherIntStream
operations before the terminal operation. In contrast,Collectors.summingInt(…)
can be combined with other collectors, e.g. used as downstream collector in agroupingBy
collector. For these use cases, there is no question about which to use.In your special case, when you are not chaining more operations nor dealing with collectors in the first place, there is no fundamental difference between these two approaches. Still, using the one which is more readable has a point. Usually, you don’t use a collector, when there is a predefined operation on the stream doing the same. You wouldn’t use
collect(Collectors.reducing(…))
when you can just use.reduce(…)
, would you?Not only is
mapToInt(mapFunc).sum()
shorted, it also follows the usual left-to-right order for what happens conceptionally, first convert to anint
, then sum theseint
s up. I think this justifies preferring this alternative over.collect(Collectors.summingInt(mapFunc))
.