简体   繁体   English

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

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: 这是使用Java 8流的方法:

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

Here is another Java 8 answer that works for objects: 这是另一个适用于对象的Java 8答案:

// 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. 您应该注意,如果您的2D数组具有不同长度的行,则“列数组”的定义不明确。 For example, how would you create the 3rd column array if the 2nd row has only 2 columns? 例如,如果第二行只有2列,您将如何创建第三列数组?

If your 2D array is a matrix (ie 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. 如果您的2D数组是矩阵(即所有行的长度都相同),则创建一个2D数组很容易,其行是原始2D数组的列。 Then you can get the columns of the original arrays easily. 然后,您可以轻松获取原始数组的列。

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 . Apache commons为此提供了工具,请查看此答案

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

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 :-要获取列的长度, out[][] 的长度请执行以下操作:-

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

Sorry I am bad at explain对不起,我不擅长解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM