Reducing 2D array stream in java

I am new to using threads in java, so here is my question. I have a double [] [] in which I want to perform the summation of elements, because I follow and aproach, similar to C # Linq, but does not seem to work.

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

The error is that acc seems to be double [], so it cannot execute double [] + double. C # Linq assumes that the battery is the same type as the seed (0 in this case). What am I missing? Thanks in advance.

+5
source share
1 answer

If you look at the reduce signature, the type of identifier should be the type of stream elements. In this case, it will be double[] . This will also give acc type double[] .

There is overload where you can put a different type of battery, but you also need to pass a combiner to combine 2 batteries.

You can do it:

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

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

Alternatively, this may be more convenient to do:

 double result = Arrays.stream(myArray) .flatMapToDouble(DoubleStream::of) .sum(); 
+5
source

Source: https://habr.com/ru/post/1266045/


All Articles