Array sorting with two comparators?

Let's say I have two comparators, primary and secondary. How can I sort an array first with a primary comparator and then with a secondary?

Let's say that each object has a name and a number field.

how

Bob 1 Bob 2 Jack 1 Jack 2 

Is this possible without creating a new comparator?

+7
source share
3 answers

Yes, you can make your choice without creating a new comparator.

There is a well-known trick for sorting by 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 must 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 guarantee stability.

Suppose your primary comparator object is stored in the primaryComp variable, and your secondary object is in secondaryComp . Then here is the code to accomplish what you want:

 Arrays.sort(mylist, secondaryComp); // This must come first! Arrays.sort(mylist, primaryComp); 
+7
source

Assuming your class

 class X { String name; int num; } 

then the 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); }}); 
+6
source

First compare the second comparator, and then the first comparator. I believe this should do the trick. You can create a class for this.

 class FullName { public String firstName; public String secondName; } 

Let's say you create a new name called BobBobbins , assign values, and then just compare the second name first, and then the first name. You may have a static function to compare:

 public static bool compareTo ( FullName name1, FullName name2 ) { // Algorithm here } 

If you are using a static comparator, you might need to do this: FullName.compareTo( BobBobbins, CharlieChaplin );

-one
source

All Articles