In the real business world, there are many cases where we're required to perform sorting on a Collection of some user-defined objects. If the element of the Collection is a
String type, or any other class which implements Comparable, then the sorting can be performed in the natural order. But sometimes, we want to perform a different criteria for sorting, or probably we want to sort a user-defined type.
Here's where Comparator comes into play. Clean and extensible.
Here's an example of a simplified user-defined type:
In the above class, the most commonly found as natural ordering would be order by lastName. This can easily be implemented using the Comparable interface, i.e.
Sorting a List of Customer objects would be as simple as:
Collections.sort (customerList);
But, if we want to use a different ordering, e.g. order by the first name, then we cannot use the natural ordering as defined within the Customer class. Instead, we have to define an alternative ordering, in the form of a Comparator class.
Sorting a List of Customer objects by their first name, would be:
// assuming you implement singleton..
Comparator comparator =
CustomerFirstNameComparator.getInstance();
Collections.sort (customerList, comparator);
Simple, clean & extensible. You can start defining more and more Comparator classes to suit your needs. As it is a
Java class, you can also perform complex comparison on the objects.