Java Comparator class to sort arrays
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
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.