Get Columns from Two Dimensional Array in Java

Get Columns from Two Dimensional Array in Java

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

7 Answers

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

You can do it like this:

for(int row = 0; row < numRows; row++) {
    colArray[row] = my2Darray[row][columnOfInterest];
}

Apache commons has tools for this, check this answer.

Here is another Java 8 answer that works for objects:

// Make 2D array of objects
Obj[][] obj = {{new Obj(0),new Obj(1)},{new Obj(2),new Obj(3)}};

// To get a row:
int rowToGet = 1;
Obj[] oRow = obj[rowToGet];

// To get a column:
int colToGet = 1;
Obj[] oCol = Arrays.stream(obj).map(o -> o[colToGet]).toArray(Obj[]::new);

// Print the row:
System.out.println(Arrays.toString(oRow));
// Print the column:
System.out.println(Arrays.toString(oCol));

// Here is the object used for this example
class Obj {
    int in;
    String str;

    public Obj(){};

    public Obj(int in){
        this.in = in;
        switch(in){
            case 0:
                str = "zero";
                break;
            case 1:
                str = "one";
                break;
            case 2:
                str = "two";
                break;
            case 3:
                str = "three";
                break;
        }
    }

    @Override
    public String toString(){
        return String.format("%d=%s",in,str);
    }
}

This will produce the output:

Extracted row: [2=two, 3=three]
Extracted col: [1=one, 3=three]

There's no easy way. You have to iterate over the array and construct the column arrays yourself.

You should note that the "column arrays" are not well defined if your 2D array has rows of different lengths. For example, how would you create the 3rd column array if the 2nd row has only 2 columns?

If your 2D array is a matrix (i.e. all the rows have the same length), it's easy enough to create a 2D array whose rows are the columns of the original 2D array. Then you can get the columns of the original arrays easily.

As Read above There is no direct way to get column length but there is a solution

out[][]=new String[a][b] // Example of multidimensional array

To get the length of columns, the length of out[][] Do this :-

String []temp = out[a] //a = index of row of which columns you want
int length = temp.legnth;

Sorry I am bad at explain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.