javaarrayssorting

sort 2D array based on two columns


I have 2D array and it has 2 columns and I want to sort this.


input is this:

first column..... second column

3......................2

4......................9

3......................1

5......................0

1......................2


output is this:

first column..... second column

5......................0

4......................9

3......................2

3......................1

1......................2


I beginner in Java.

please help me whit a code of function(mySort(int[][] arr) to sort the array.


Solution

  • You can sort with your custom comparator:

    Arrays.sort(datas, new Comparator<Integer[]>() {
             @Override
             public int compare(Integer[] entry1, Integer[] entry2) {
                    if(entry1[0] == entry2[0]){
                           return entry2[1] - entry1[1];
                    }
                    return entry2[0] - entry1[0];
             }
    });