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];
}
Here’s a complete example using Java 8:
Output:
For Java 7 you can do:
If you unfortunate enough to work on Java 6 or older, you’d do: