Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following function compare obj1 with obj2
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an array/ArrayList of our own class type, containing fields like roll no, name, address, DOB, etc and we need to sort the array based on Roll no or name?
Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No. and Name.
Method 2: Using the comparator interface- Comparator interface is used to order the objects of the user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else.
We need to use Collections.sort() for this:
How do Collections.Sort() work?
Internally the Sort method does call the are a thod of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0 or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for their sort.
To read more about this click here
Task:
As you have created a class pair in previous examples so here also we need to use that example.
You are given N pairs and you need to sort them in Scaler Sorted Order.
In Scaler Sorted Order you need to order the pairs in terms of decreasing value of second attribute and if second attribute of two object is same then order them in decreasing value of first attribute.
Input and output is already handled in the snippet mentioned below, you just need to create pair class which: