Java 8 Streams – Why can't I sum a Stream of Integers?

  • A+
Category:Languages

Given a list of Integer's: List<Integer> numbers = Arrays.asList(1,2,3);

Why can't I sum them like: numbers.stream().sum();?

Instead I have to do this: numbers.stream().mapToInt(e -> e).sum();

I know that mapToInt produces an IntStream, the primitive specialization. But still I don't get it. Why can't it sum Integers? I know that this list has Integers and the compiler should be able to do the same. After all it can now infer type parameters in lambda expressions.

OK, an Integer could be null and sum would fail. But I could take responsibility for that and filter null out:

numbers.stream().filter(Objects::nonNull).sum();

Why can't I sum a Stream of Integers?

 


Calling stream() on a List will get you a general-purpose Stream, which can handle any reference type, not just numeric types. It doesn't make sense to include a sum method on Stream, because it doesn't make sense to sum URLs, Classes, Threads, or any other non-numeric reference type.

You could sum the elements by calling reduce:

numbers.stream().reduce(0, (a, b) -> a + b) 

But that would involve a lot of unboxing and boxing. It would be best to sum them as you have it, by converting it to an IntStream, which operates on ints, and calling sum() (or summaryStatistics(), which includes count, average, max, and min along with sum).

You could even use IntStream.of and avoid boxing the values even once.

IntStream.of(1, 2, 3).sum() 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: