Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements based on any data member. For instance it may be on rollno, name, age or anything else.
Syntax of compare method
public int compare(Object obj1,Object obj2): compares the first object with second object.
Collections class provides static methods for sorting the elements of collection. If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator.
Example of sorting the elements of List that contains user-defined class objects on the basis of age and name
In this example, we have created 4 java classes:
- Student.java
- AgeComparator.java
- NameComparator.java
- Simple.java
This class contains three fields rollno, name and age and a parameterized constructor.
This class defines comparison logic based on the age. If age of first object is greater than the second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first object is less than the second object, we are returning negative value, it can be any negative value and if age of both objects are equal, we are returning 0.
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.
In this class, we are printing the objects values by sorting on the basis of name and age.
Output:Sorting by Name... 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by age... 105 Jai 21 101 Vijay 23 106 Ajay 27
No comments:
Post a Comment