In my previous post we saw Comparable and it’s implementation. Java provides another way to compare objects. Instead of implementing the comparable interface, we can implement the Comparator interface.
The main difference between these two interfaces is that the comparable interface defines one method compareTo(), which takes one parameter.
The comparator interface defines one method compare() that takes two parameters (of the same type) and returns the comparison of these two objects.
Lets see implementation of comparator
Lets break it down:
- We created an Comparator object which takes Argument as User.
- It implements compare method which takes 2 User object.
- Inside compare we define how we need to compare User’s object in this case by age ASC It returns int 0, -1, 1 based on comparison
- Same as AGEORDER except that it adds extra condition for further sorting if age’s are equal.
- The only difference is it’s defined in another class. Just another way to define Comparator
Note: To sort object in descending order just change order of Obj in compareTo as done in AGEANDNAME