HectorBarbossa HectorBarbossa - 8 months ago 20
Java Question

Computing sum and sum-of-squares at the same time with Streams

I was wondering if there is any way to achieve the following within a single iteration over the array. Simply to have two different results out of stream.

double sum = Arrays.stream(doubles).sum();
double sumOfSquares = Arrays.stream(doubles).map(d -> d * d).sum();


Well, you could with a custom collector, for instance:

double[] res =
          .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 you don't gain much readability in my opinion, so I would stick with the multiple passes solution (or maybe just use a for-loop in this case).