You are looking at the intersection of two otherwise distinct use cases. Using mapToInt(…)
allows you to chain other IntStream
operations before the terminal operation. In contrast, Collectors.summingInt(…)
can be combined with other collectors, e.g. used as downstream collector in a groupingBy
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 an int
, then sum these int
s up. I think this justifies preferring this alternative over .collect(Collectors.summingInt(mapFunc))
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…