Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find array column sum using Java streams

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.

like image 518
vybiar Avatar asked Aug 29 '26 06:08

vybiar


1 Answers

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.

like image 106
Willem Van Onsem Avatar answered Aug 31 '26 19:08

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!