Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Array stream reduce in java

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.

like image 987
Vicsufer Avatar asked Mar 28 '17 21:03

Vicsufer


People also ask

What does reduce () method does in stream?

Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.

What is reduce in Java 8 streams?

A reduction is a terminal operation that aggregates a stream into a type or a primitive. The Java 8 Stream API contains a set of predefined reduction operations, such as average , sum , min , max , and count , which return one value by combining the elements of a stream.

Can you change the size of a 2D array Java?

Similar to the one-dimensional array, the length of the two-dimensional array is also fixed. You can not change the length of an array, I mean, the number of rows and columns will remain fixed.

How do you modify a 2D array in Java?

In Java, elements in a 2D array can be modified in a similar fashion to modifying elements in a 1D array. Setting arr[i][j] equal to a new value will modify the element in row i column j of the array arr .


1 Answers

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();
like image 172
Jorn Vernee Avatar answered Sep 21 '22 18:09

Jorn Vernee