Is mapToDouble() really necessary for summing a List<Double> with Java 8 streams? -


as far can tell, way sum list<double> using java 8 streams this:

list<double> vals = . . . ; double sum = vals.stream().maptodouble(double::doublevalue).sum(); 

to me, maptodouble(double::doublevalue) seems kind of crufty - sort of boilerplate "ceremony" lambdas , streams supposed dispense with.

best practices tell prefer list instances on arrays, , yet sort of summing, arrays seem cleaner:

double[] vals = . . . ; double sum = arrays.stream(vals).sum(); 

granted, 1 this:

list<double> vals = . . . ; double sum = vals.stream().reduce(0.0, (i,j) -> i+j); 

but reduce(....) longer sum().

i has way streams need retrofitted around java's non-object primitives, still, missing here? there way squeeze autoboxing in make shorter? or current state of art?


update - answers digest

here digest of answers below. while have summary here, urge reader peruse answers in full.

@dasblinkenlight explains kind of unboxing necessary, due decisions made further in history of java, in way generics implemented , relationship non-object primitives. notes theoretically possible compiler intuit unboxing , allow briefer code, has not yet been implemented.

@holger shows solution close expressiveness asking about:

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

i unaware of new static double.sum() method. added 1.8, seems intended purpose describing. found double.min() , double.max(). going forward, use idiom such operations on list<double> , similar.

to me, maptodouble(double::doublevalue) seems [what] lambdas , streams supposed dispense with.

the need use maptodouble consequence of decision implement generics via type erasure, closing door on possibility of using primitives inside generics. same decision made necessary create doublestream, intstream, , longstream family of classes - provide stream-based unboxing.

is there way squeeze autoboxing in make shorter? or current state of art?

unfortunately, not @ time: although theoretically possible compiler figure out stream<double> can converted doublestream implicitly, in same way primitives unboxed, has not been done.

as far array-based solution goes, efficient of three. however, not flexible other two: 1 maptodouble lets sum attribute of custom class, while last 1 lets perform other types of aggregation.

reduce(....) longer sum()

i agree, approach worse maptodouble in terms of readability.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -