java 2d array secondary sort

303 views Asked by At

I want to sort the following 2D array so, that the first index of each row is ascending and if it is the same in 2 rows, that the second index also is sorted ascending. Example: given:

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

I want it to be arr = {{1,1},{1,2},{1,3},{1,4},{1,5},{2,1},{2,2},{2,3},{2,4},{2,5}};

It worked for me to sort by first index using:

Arrays.sort(arr, Comparator.comparingInt(arr -> arr[0]));

Now my idea was to cut it down into sub-arrays, sort them and merge them back together, but i really wanted to know if there is a better way to do it I am not aware of. ( maybe even using the comparator, thx in advance )

1

There are 1 answers

1
pero_hero On BEST ANSWER

you can add a second comparator to the first one by using thenComparing, which basically leads to a behaviour that if the first comparator returns an equal result the second comparator is used to break the tie:

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

        Comparator<int[]> first = Comparator.comparingInt(a -> a[0]);
        Comparator<int[]> second = Comparator.comparingInt(a -> a[1]);

        Arrays.sort(arr2, first.thenComparing(second));

        for(int i = 0; i< arr2.length; i++){
            System.out.println(arr2[i][0] + "," + arr2[i][1]);
        }

it is also possible to create a more succinct version of the comparator, by using thenComparingInt:

Comparator<int[]> cp = Comparator.<int[]>comparingInt(a -> a[0]).thenComparingInt(a -> a[1]);