Pedro Gonzalez
Pedro Gonzalez

Reputation: 1459

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

Upvotes: 8

Views: 72401

Answers (7)

Prime Balpreet
Prime Balpreet

Reputation: 16

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

Upvotes: 0

Geoffrey Hayward
Geoffrey Hayward

Reputation: 53

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

Upvotes: 3

Buzzaard
Buzzaard

Reputation: 21

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]

Upvotes: 2

sprinter
sprinter

Reputation: 27956

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

Upvotes: 13

Eric Leibenguth
Eric Leibenguth

Reputation: 4277

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

Upvotes: 14

Jonas Czech
Jonas Czech

Reputation: 12328

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.

Upvotes: 1

Eran
Eran

Reputation: 393821

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.

Upvotes: 0

Related Questions