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:
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:
Why can't I sum a Stream of Integers?
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
Threads, or any other non-numeric reference type.
You could sum the elements by calling
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
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()