Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array given two comparators?

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?

like image 406
Jack Avatar asked Mar 06 '13 06:03

Jack


People also ask

Can we sort array using 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.

How do I sort by Comparator?

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.

How do I sort two arrays together?

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.

How do you sort an ArrayList of pairs?

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.


2 Answers

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);
like image 184
Nayuki Avatar answered Oct 18 '22 07:10

Nayuki


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);
        }});
like image 23
Evgeniy Dorofeev Avatar answered Oct 18 '22 06:10

Evgeniy Dorofeev