Comparator is used when we want to sort a collection of objects which can be compared with each other. This comparison can be done using Comparable interface as well, but it restrict us compare the objects in a natural order. If we want to sort this collection, based on multiple criterias/fields, then Comparator can be used for this purpose.
We will use Student with four attributes id, firstName, lastName and age.
Basic use case, where list of students will be sorted based on their first name.
What if we want to sort on first name but in revered order? really easy solution is to use reversed() method.
Here we are sorting list of students first by their first name, and then sort again the list of last name. Just as we apply sorting on SQL statements. It’s actually a very good feature.
Now you don’t need to always use sorting on multiple fields in SQL select statements, you can sort them in java as well.
You can sort the collection of objects in parallel using multiple threads as well. It is going to be very fast if collection is big enough having thousands of objects. For small collection of objects, normal sorting is good enough and recommended.