In a two dimensional array I can easily get the arrays for the rows, how can I get the columns as arrays too? I need a solution that works for objects too, not just primitives. Thanks
int counter = 1;
int[][] matrix = new int[9][9];
for (int x = 0; x < matrix.length; x++) {
for (int y = 0; y < matrix[0].length; y++) {
matrix[x][y] = counter;
System.out.print(counter + " ");
counter++;
}
System.out.println();
}
for (int x = 0; x < matrix.length; x++) {
int[] row = matrix[x];
}
The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .
2D array can have 1D arrays as elements in it. So, matrix[int index] will give you 1D array to pass it to the method. So either change method declaration to print(double[][] vectors) or pass matrix[index] as method parameter. You can call the method by instance of you class.
There's no "out-of-the-box" way, but you can create a static method for this:
public static Object[] getColumn(Object[][] array, int index){
Object[] column = new Object[array[0].length]; // Here I assume a rectangular 2D array!
for(int i=0; i<column.length; i++){
column[i] = array[i][index];
}
return column;
}
Here is a method using Java 8 streams:
int[] getColumn(int[][] matrix, int column) {
return IntStream.range(0, matrix.length)
.map(i -> matrix[i][column]).toArray();
}
And if you want to cope with rows that are too short:
int[] getColumn(int[][] matrix, int column, int defaultVal) {
return IntStream.range(0, matrix.length)
.map(i -> matrix[i].length < column ? defaultVal : matrix[i][column])
.toArray();
}
You can do it this way:
private <T> T[] getColumn(int address, T[][] from) {
return (T[]) Arrays.stream(from).map(x -> x[address]).toArray(Object[]::new);
}
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