Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collectors.summingInt() vs mapToInt().sum()

Tags:

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?

like image 568
thecoop Avatar asked May 04 '16 09:05

thecoop


People also ask

What does collectors toList () do?

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) .

What is the easiest way to print the sum of all of the numbers present in a List using Java 8?

mapToInt(Integer::intValue) . sum();

Which stream operations are needed to get sum of all even numbers from stream of integer values?

Stream has a sum() method that when used with filter() gives the required result easily.

What is the use of collectors toList in Java?

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.


1 Answers

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 ints up. I think this justifies preferring this alternative over .collect(Collectors.summingInt(mapFunc)).

like image 72
Holger Avatar answered Sep 24 '22 02:09

Holger