Reputation: 63
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.
Upvotes: 6
Views: 1436
Reputation: 33885
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();
Upvotes: 6