Java – get columns from two dimensional array in java

javamultidimensional-array

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];  
    }

Best Solution

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;
}