How Comparator compare Method Works

Java Comparator & compare

In the past example on Comparable Interface, we built Natural Sorting Order for our Product class by overriding the compareTo method. We did this sorting in the Product class itself. Then we used the Product as TreeSet Items. This means, does TreeSet support only one sorting? No, we can define custom sorting also. We can define it through a user class which signs the Comparator Interface and overrides its compare method. We can define one or many custom sorting orders using the Comparator Interface. For example, Sorting the product by its name in Ascending and descending order can be done through Java Comparator Interface.