I'm a complete newbie to API stream, and I want to do some operation on a 2D array
The following code is a simplified version of what I want to do.
I have an array of values :
int values[][] = new int[][] {{1,2},{3,4},{5,6}};
I'd like to process values per column and get
int result[] = {x,y}
For example, if I do a sum, it should get me
result[] = {9, 12}
Thanks by advance for your help
Try this.
int values[][] = new int[][] { { 1, 2
}, { 3, 4
}, { 5, 6
}
};
int[] v = Arrays.stream(values).reduce(new int[] { 0, 0
}, (a, b) ->
{
a[0] += b[0];
a[1] += b[1];
return a;
});
System.out.println(Arrays.toString(v));
EDIT:
In regards to your other question about accomodating different number of columns. Yes you can do it. But just because you can doesn't mean you should or that it's the best way. What follows is a simple method that sums up integers in any 2D array regardless of row length. It even handles ragged arrays. Note that this sums up the columns, first come, first served basis as they are treated as though they are left justified relative to each other.
Initialize a irregular (ragged or different row length) array
int values[][] = new int[][] { { 1
}, { 20, 3
}, { 1, 2, 4
}, { 3, 4, 10
}, { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
};
Now compute the sum using the following method.
public static int[] sumColumns(int[][] vals) {
// compute the maximum row length (most columns)
int maxColumns = 0;
for (int r = 0; r < vals.length; r++) {
maxColumns = Math.max(maxColumns, vals[r].length);
}
// use that to initialize the return array
int[] sums = new int[maxColumns];
//now just iterate over the rows and columns
// calculating the sum.
for (int r = 0; r < vals.length; r++) {
for (int c = 0; c < vals[r].length; c++) {
sums[c] += vals[r][c];
}
}
return sums;
}
To do any rectangular matrix with streams, do the following:
int[] result2 =
Arrays.stream(values).reduce(new int[values[0].length], (a, b) ->
{
for (int i = 0; i < values[0].length; ++i) {
a[i] += b[i];
}
return a;
});