I have a 2D integer array:
int arr[][] = new int[rows][columns];
The nth Row sum can be found using:
int rSum=Arrays.stream(arr[n]).sum();
How can I find the pth Column sum?
int cSum=Arrays.stream(arr[][p]).sum();
The above line does not work.
You can map every row on the p-th element:
int cSum = Arrays.stream(arr).mapToInt(row -> row[p]).sum();
This works as follows: first we construct a stream from the arr. This stream will contain the rows of the "matrix". Then for every such row, we mapToInt it to an int: the p-th element of that row. Then we sum(..) the stream of ints together to the sum.
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