HectorBarbossa HectorBarbossa - 2 years ago 91
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();

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download