Calculation of the sum and sum of squares simultaneously with the flows

I was wondering if there is a way to achieve the next in one iteration over the array. Just have two different results from the stream.

double sum = Arrays.stream(doubles).sum(); double sumOfSquares = Arrays.stream(doubles).map(d -> d * d).sum(); 
+5
source share
1 answer

Well, you could use a custom collector, for example:

 double[] res = Arrays.stream(doubles) .collect(() -> new double[2], (arr, e) -> {arr[0]+=e; arr[1]+=e*e;}, (arr1, arr2) -> {arr1[0]+=arr2[0]; arr1[1]+=arr2[1];}); double sum = res[0]; double sumOfSquares = res[1]; 

but, in my opinion, you are not getting more readability, so I would stick with a multi-pass solution (or maybe just use a for-loop in this case).

+13
source

All Articles