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?
toList. Returns a Collector that accumulates the input elements into a new List . There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier) .
mapToInt(Integer::intValue) . sum();
Stream has a sum() method that when used with filter() gives the required result easily.
The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method can be used.
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With