Is mapToDouble() really necessary for summing a List with Java 8 streams?

Is there some way to squeeze autoboxing in to make this shorter?

Yes, there is. You can simply write:

double sum = vals.stream().mapToDouble(d->d).sum();

This makes the unboxing implicit but, of course, does not add to efficiency.

Since the List is boxed, unboxing is unavoidable. An alternative approach would be:

double sum = vals.stream().reduce(0.0, Double::sum);

It does not do a mapToDouble but still allows reading the code as “… sum”.

Leave a Comment