简体   繁体   English

如何根据第二列对二维数组中的第一列进行排序?

[英]How to sort the first column in a 2-dimensional array based on the second?

For example: 例如:

My first column in the array is at first numerically in order. 我在数组中的第一列首先按数字顺序排列。 The Second column is numerically random. 第二列是数字随机的。 I want to place the second column in order, which of course will force the first column out of order. 我想按顺序放置第二列,这当然会强制第一列乱序。 Any ideas how to do this in java. 任何想法如何在java中这样做。 I have searched, but can't seem to find the vocabulary to properly find it. 我已经搜索过,但似乎无法找到正确找到它的词汇。

The method you can use is one of the Arrays.sort() , where you define your own comparator, which can compare two rows of a two-dimensional array. 您可以使用的方法之一是Arrays.sort() ,您可以在其中定义自己的比较器,它可以比较二维数组的两行。

The code below allocates an array with two columns and ten rows, with the first column sorted and the second one completely random. 下面的代码分配一个包含两列和十行的数组,第一列已排序,第二列完全随机。 Then it sorts it according to the second column. 然后根据第二列对其进行排序。

class Test{

    static void print(int[][] a){
        for (int i=0;i<a.length;i++){
            for (int j=0;j<a[0].length;j++) 
                System.out.print(a[i][j]+" ");
            System.out.println();
        }
    }

    public static void main(String[]args){

        java.util.Random r = new java.util.Random();
        int[][] a = new int[10][2];
        for (int i=0;i<a.length;i++){
            a[i][0]=i+1;
            a[i][1]=r.nextInt(100);
        }

        print(a);
        System.out.println();

        java.util.Arrays.sort(a, 
            new java.util.Comparator<int[]>(){
                public int compare(int[]a,int[]b){
                    return a[1]-b[1];
                }
        });

        print(a);
    }
}

Example output: 示例输出:

1 8 
2 49 
3 82 
4 89 
5 8 
6 0 
7 83 
8 89 
9 8 
10 46 

6 0 
1 8 
5 8 
9 8 
10 46 
2 49 
3 82 
7 83 
4 89 
8 89 

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

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