Home > Back-end >  Sort a 2-D array in Java based on one parameter first and then based on the second. [JAVA]
Sort a 2-D array in Java based on one parameter first and then based on the second. [JAVA]

Time:01-31

Let's say I have a 2-D array arr[][]:

col1 col2
[1, 7]
[2, 6]
[3, 9]
[4, 1]
[5, 3]
[6, 7]

and we have to sort it based on col1 1st and then based on col2

What is the way to do this in Java? Particularly how can we use comparator to achieve the same?

CodePudding user response:

Try this, using comparator chaining:

Arrays.sort(arr, Comparator.<int[]>comparingInt(arr1 -> arr1[0]).thenComparing(arr1 -> arr1[1]));
System.out.println(Arrays.deepToString(arr));

CodePudding user response:

One way to the following using comparator would be:

Arrays.sort(arr, (a,b) -> a[0] != b[0] ? a[1]-b[1] : a[0]-b[0]);
  • Related