1. About Comparator Interface & compare Method
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. In this example, we will provide one sorting for our Product class.
2. Java Comparator Interface & Custom Sorting
The Comparator interface helps to sort Java Collection frame-work. For example, Collection.sort and Arrays.sort utility methods (static) will take the Comparator object to do sorting. Java Collection framework classes which implement SortedSet and SortedMap interfaces can make use of this Comparator for keeping the items in a sorted way. This interface has a method called compare, which one can use to write their custom sorting logic. In this example, we will use this Comparator to sort the Product object by its name. Then we will tell the TreetSet to use this Comparator class.
3. The compare Method of Java Comparator
In the last example about Comparable Interface, we learnt about the compareTo method. Now, let us look at the compare method of the Comparator Interface. Below is the signature of the compare method:

From the picture, we can conclude that the compare method takes two objects that needs to be compared. In case of TreeSet, the item e1 is fixed and item e2 is changed by java algorithm. Means, Java API function like add(E e1) will make a call to compare by pushing e2 from its existing collection items. This happens till e1’s position is fixed in the TreeSet. From the return value, the collection class like TreeSet know how to order the items. Now, have a look at the below picture:

The above picture tells how item e1 is added to the existing collection of five items. The compare logic will fit the item e1 between 9 and 6. The logic here works the same way how compareTo method works. Note how the collection item e2 is placed first in the return statement to get descending order. Our Product class already has Natural Sorting Order via the Comparable interface. Now, it is time to go on with the example.
4. Code Example – compare Usage
4.1 Sorting Product Via Java Comparator
We know our Product
Class is Natural Sorting Order compatible via the Comparable Interface
. Now, we will setup the custom sorting order for it. First, we need to create a class which signs Comparator
Interface. Then write a compare
method which takes two Product
object as arguments and aids the compare action by returning an integer. Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 |
//Sample 02: Define Custom Sorting Order //Using Comparator import java.util.Comparator; public class ProdIdDesc implements Comparator<Product> { @Override public int compare(Product fixed, Product element) { //Param1 is Fixed //Param2 is picked from collection return element.getProdId() - fixed.getProdId(); } } |
In the above code, we define a class ProdIdDesc
which implements the
Comparator interface. Note the Comparator
is for the Product class and you can see that in line 4
Comparator<Product>. In the
compare method body, we use the ProdId
member to go on with the comparison. Note, we kept the fixed part as the 2nd operand for the – operator. These operands are swapped when we compared two Products in our past example on Comparable Interface. Recall, the Comparable is for defining the Natural Sorting Order. Now, this
compare method is defining the sorting in descending order of Product Id.
4.2 TreeSet using the Java Comparator
We create our TreeSet to use the Comparator created in the previous step. In the below code, at line 1, we create an instance of the Comparator ProdIdDesc. Then we give this Comparator to the TreeSet while constructing it. Now, when we add the elements to the TreeSet, it makes use compare method of Comparator in place of compareTo of the Comparable. This will end the sorting in Descending Order of Product Id. Note, you can implement as many comparator as you want. Say, for example, we can write one more Comparator which sorts the Products by its name in Ascending order or in Descending order.
1 2 3 4 |
//Sample 03: Create Tree Set with Custom Sorting Order //Product ID desc ProdIdDesc comparator = new ProdIdDesc(); SortedSet<Product> set = new TreeSet<Product>(comparator); |
Now if we add elements and print it, the TreeSet prints the collection items in Descending order of Product Id.
5. Complete Example – Java Comparator Interface
Product.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.Objects; public class Product implements Comparable{ private int ProdId; private String ProdName; Product(int id, String name) { ProdId = id; ProdName = name; } @Override public String toString() { return ProdId + ":" + ProdName ; } public int getProdId() { return ProdId; } public void setProdId(int prodId) { ProdId = prodId; } public String getProdName() { return ProdName; } public void setProdName(String prodName) { ProdName = prodName; } @Override public int hashCode() { return Objects.hashCode(ProdId); } @Override public boolean equals(Object obj) { Product prod = (Product) obj; return (this.ProdId == prod.getProdId()); } @Override public int compareTo(Object o) { Product element = (Product)o; return this.ProdId - element.getProdId(); } } |
ProdIdDesc.java
1 2 3 4 5 6 7 8 9 10 11 12 |
//Sample 01: Define Custom Sorting Order //Using Comparator import java.util.Comparator; public class ProdIdDesc implements Comparator<Product> { @Override public int compare(Product fixed, Product element) { //Param1 is Fixed //Param2 is picked from collection return element.getProdId() - fixed.getProdId(); } } |
TreeSetNumber.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
//Sample 01: Package Required import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; public class TreeSetNumber { public static void main(String[] args) { //Sample 02: Create Tree Set with Custom Sorting Order //Product ID desc ProdIdDesc comparator = new ProdIdDesc(); SortedSet<Product> set = new TreeSet<Product>(comparator); //Sample 03: Create six Products Product p1 = new Product(101, "Pen"); Product p2 = new Product(102, "Pencil"); Product p3 = new Product(103, "Rubber"); Product p4 = new Product(104, "Writing Pad"); Product p5 = new Product(105, "Clips"); Product p6 = new Product(106, "Sharpner"); //Sample 05: Add Elements & Ensure Sorting of Custom Object set.add(p2); set.add(p4); set.add(p1); set.add(p3); set.add(p6); set.add(p5); printTree(set); } //Sample 04: Traverse and Print the the Tree private static void printTree(SortedSet<Product> set) { Iterator<Product> itr = set.iterator(); while (itr.hasNext()) System.out.print(itr.next() + ","); System.out.println(); } } |
6. Watch Comparator & compare Example as YouTube
Categories: Java
Tags: Comparator, compare method