Say, we have the following 2-dimensional array:
int camels[][] = new int[n][2];
How should Java Comparator
class be declared to sort the arrays by their first elements in decreasing order using Arrays.sort(camels, comparator)
? The compare
function for reference is:
@Override public int compare(int[] a, int [] b)
{
return b[0] - a[0];
}
This question is related to
java
arrays
multidimensional-array
comparator
Just tried this solution, we don't have to even write int.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);
This thing will also work, it automatically detects the type of string.
The answer from @aioobe is excellent. I just want to add another way for Java 8.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);
System.out.println(Arrays.deepToString(twoDim));
For me it's intuitive and easy to remember with Java 8 syntax.
Source: Stackoverflow.com