简体   繁体   中英

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.

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:

  1. Empty arrays as last

  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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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