简体   繁体   English

如何使用 java 中的比较器对二维数组进行排序

[英]How to sort two dimensional array using Comparator in java

I need to sort such an array by descending the elements of the first column.我需要通过对第一列的元素进行降序来对这样的数组进行排序。 In the case of equality of elements in the first column, the elements of the second column must be sorted in ascending order.在第一列元素相等的情况下,第二列元素必须按升序排序。 But this what I need else is to check and put empty row to the end of matrix, and row with only one element put prior to the same which has more elements.但这我需要的是检查并将空行放在矩阵的末尾,并且只有一个元素放在具有更多元素的相同元素之前的行。 For example in this array {3} - it is the first row, {} - the last one.例如,在这个数组中{3} - 它是第一行, {} - 最后一行。

int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2}, {3, 3, 5}};

 Arrays.sort(arr, new Comparator<int[]>() {
     @Override
     public int compare(int[] o1, int[] o2) {
        if(o1[0] == o2[0])
            return o1[1] - o2[1];
        return o2[0] - o1[0];
    }
});

for (int[] ints : arr) {
    for (int anInt : ints) {
        System.out.print(anInt + " ");
    }
    System.out.println();
}

The following Comparator<int[]> enables sorting by:以下Comparator<int[]>启用排序方式:

  1. Empty arrays as last最后清空 arrays

  2. Bigger number at the same index in the ascending order同一索引处较大的数字按升序排列

  3. In case the smaller array first into larger (in terms of length) starting at index 0, which one comes first is considered smaller compared to the latter one.如果从索引 0 开始,较小的数组首先变成较大的(就长度而言),则与后一个相比,先出现的数组被认为更小。

Here is an algorithm can be easily modified according to your needs:这是一个可以根据您的需要轻松修改的算法:

int[][] arr = {{1, 2, 3}, {}, {3}, {1, 4}, {3, 2, 2}, {3, 3, 5}, {3, 2}};

Arrays.sort(arr, (o1, o2) -> {
        if (o1.length == 0) { return 1; }         // empty last
        if (o2.length == 0) { return -1; }        // empty last
        int min = Math.min(o1.length, o2.length); // upper bound to avoid ArrayIndexOutOfBoundsException
        for (int i = 0; i < min ; i++) {
            if (o1[i] != o2[i]) {                 // compare values on indices
                return o1[i] - o2[i];             // return if different
            } 
        }
        return 1;                                 // it goes first so it lefts first
    }
);

System.out.println(Arrays.deepToString(arr)); 

The output will be: output 将是:

[[1, 2, 3], [1, 4], [3], [3, 2, 2], [3, 2], [3, 3, 5], []] [[1, 2, 3], [1, 4], [3], [3, 2, 2], [3, 2], [3, 3, 5], []]

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

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