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

  • A+

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

Why can't I sum them like:;?

Instead I have to do this: -> 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:;

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:, (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() 


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