Comparator interface sorts the objects of user-defined classes. An object of the Comparator class is capable of comparing two objects of two different classes. Following function compare obj1 with obj2
- TreeSet implements the SortedSet interface. So, duplicate values are not allowed.
- Objects in a TreeSet are stored in a sorted and ascending order.
- TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
- If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow inserting Heterogeneous objects. It will throw a classCastException
Since TreeSet implements the sortedSet interface, therefore, the elements by default are sorted in ascending order. But if we want to change in the Sorting like to make it in decreasing order or sorting on the basis of name, marks, Salary (these all are user-defined classes) like in any ways.
So the solution to all this that we can do the sorting by implementing the comparator class Explicitly.
public int compare(Object obj1, Object obj2):
- 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 marks, name, or anything else.
Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.
// To sort a given list. ComparatorClass must implement // Comparator interface. public void sort(List list, ComparatorClass c)
-------increasing Order with the Marks Daniel 134 Ronaldo 341 Sam 450 George 590 Daniel 134 George 590 Ronaldo 341 Sam 450
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.