What is the syntax for using IntStream to sum a range of elements in a 2D array?
For a 1D array, I use the following syntax:
int totalElementsInArray = 0;
totalElementsInarray = IntStream.of(myArray).sum();
So for instance, say I have a 2D array:
int[][] my2DArray = new int[17][4];
What is the syntax when using IntStream for summing columns 0-16 on row 0?
int totalElementsInArray = 0;
totalElementsInarray = IntStream.of(my2DArray[0 through 16][0]).sum();
You just need to map each sub-array to an int
by taking the first element:
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String args[]) {
int[][] data = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int sum = Arrays.stream(data)
.mapToInt(arr -> arr[0])
.sum();
System.out.println(sum); // 5, i.e. data[0][0] + data[1][0]
}
}
In other words:
data
to a Stream<int[]>
(i.e. a stream of simple int
arrays)IntStream
I prefer this approach over the approaches using range
, as there seems no need to consider the indexes of the sub-arrays. For example, if you only had an Iterable<int[]> arrays
you could still use StreamSupport.stream(arrays.spliterator(), false).mapToInt(arr -> arr[0]).sum()
, whereas the range approach would require iterating multiple times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With