Say I have two comparators, a primary and a secondary. How can I sort an array first by the primary comparator, then by the secondary?
Say each object has a name and a number field.
Like
Bob 1
Bob 2
Jack 1
Jack 2
Is it possible without creating a new comparator?
One of the utility method Arrays. sort() helps us to sort an Array of objects by passing Comparator object, where Comparator holds the sorting logic.
To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.
Approach: Store the pairs in an array using a user-defined Pair class. Override the comparator method to sort the array according to the first element. Sort the array according to the first element.
Yes, you can accomplish your sort without creating a new comparator.
There is a well-known trick for sorting by a primary field, secondary, tertiary, etc: First sort by the least important field (tertiary), then the next important field (secondary), and finally the most important field (primary). But the sorting algorithm needs to be stable for this to work.
If you are sorting an array, use Arrays.sort()
. If you are sorting a List
, use Collections.sort()
. Both of these methods are guaranteed to be stable.
Suppose your primary comparator object is stored in the variable primaryComp
, and your secondary is in secondaryComp
. Then here is some code to accomplish what you want:
Arrays.sort(mylist, secondaryComp); // This must come first!
Arrays.sort(mylist, primaryComp);
assuming your class is
class X {
String name;
int num;
}
then sorting will be
Arrays.sort(x, new Comparator<X>() {
@Override
public int compare(X o1, X o2) {
if (o1.name.equals(o2.name)) {
return Integer.compare(o1.num, o2.num);
}
return o1.name.compareTo(o2.name);
}});
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