2

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 )

2
  • 1
    Depending on how much you know about sorting-algorithms I would suggest you read about different ways to sort an array. When it comes to your question it might be a duplicate to stackoverflow.com/questions/15452429/java-arrays-sort-2d-array. Although you might want a different answer. Commented Apr 7, 2020 at 20:03
  • i know some sorting algorithms through university, but we did not go into as much detail regarding this case in particular. i saw the thread you linked earlier as well, but could not make much of it, since his examples do not have duplicates in one index, where he wanted to sort the other one. i was hoping for my question not to be a duplicate as well Commented Apr 7, 2020 at 20:11

1 Answer 1

4

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

this piece of syntax " first.thenComparing(second) " is precisely what i was looking for, thank you very much! solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.