6

I'm new to using streams in java and I have a question on using streams. I have a double[][] in which i want to perform the summation of elements, for it I've written the following approach similar to C#Linq, but it doesn't seem to work.

Arrays.stream(myArray).reduce(0,(acc, i) -> acc + Arrays.stream(i).sum());

The error is that acc seems to be a double[], so it can't perform double[]+double. In C#Linq the accumulator is assumed to be the same type as the seed(0 in this case). What am I missing here? Thanks in advance.

1 Answer 1

6

If you look at the signature of reduce, the type of the identity has to be the type of the stream's elements. Which would be double[] in this case. That would also give acc the type of double[].

There is an overload where you can supply an accumulator of a different type, but you also need to pass a combiner, to combine 2 accumulators.

You can do this:

double result = Arrays.stream(myArray)
    .reduce(0D, (acc, i) -> acc + Arrays.stream(i).sum(), Double::sum);

Where 0D is a double literal, and Double::sum is used to combine 2 accumulators.

Alternatively, it might be more convenient to do this:

double result = Arrays.stream(myArray)
    .flatMapToDouble(DoubleStream::of)
    .sum();
Sign up to request clarification or add additional context in comments.

2 Comments

flatMap is the cleanest approach.
I’d prefer Arrays.stream(myArray) .flatMapToDouble(Arrays::stream) .sum(); as this is not a varargs use case. And Arrays::stream is even shorter than DoubleStream::of

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.