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]; }
The Comparator interface imposes the total ordering of on some collection of objects, through contract of the compare() method. The Arrays. sort(objectArray) method only works with a collection of objects that implement the Comparable interface, i.e. have natural ordering.
Using Comparator we can sort ArrayList on the basis of multiple variables. We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface.
public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.
Arrays class has a method called sort() which can be used to sort an array in-place.
[...] 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]); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With