Comparable vs Comparator

Dasari Swaroop Kumar
3 min readNov 15, 2020

In this article, we will talk about Comparable(I) and Comparator(I) in Java collections wrt TreeSet.

Comparable Interface:

It is present in java.lang package and it contains only one method compareTo().

Method Signature:

public int compareTo(Object obj);

Method Usage:

obj1.compareTo(obj2)

The above statement, returns -ve value if obj1 has to come before obj2. returns +ve value if obj1 has to come after obj2. returns zero if obj1 and obj2 are equal.

In TreeSet, if we are depending on the default natural sorting order while adding objects into TreeSet, JVM will call the compareTo() method, internally.

Example program:

package com.example.helloworld;

import java.util.TreeSet;

public class HelloWorld{

public static void main(String[] args) {
TreeSet t=new TreeSet();
t.add("K");//line-1
t.add("Z");//line-2
t.add("A");//line-3
t.add("A");//line-4
//t.add(new StringBuffer("L")); check the output after adding this line.
System.out.println(t);//[A,K,Z]

}
}

Let me explain how we get that output,

line-1 will create a node with String “K” containing in it.

when line-2 is executed, the value “Z” is compared with “K”. ie., line-2 uses the compareTo() method, to see if “Z” comes before “K” or after “K”. since the result evaluates toafter K’, Z is placed after K in the tree Structure.

when line-3 is executed, the value of “A” is compared with “K” first, since “A” comes before “K”, “A” moves to the left of “K” in the tree structure and places itself there.

when line-4 is executed, the value of “A” is compared with “K” first, since “A” comes before “K”, “A” moves to the left of “K” in the tree structure and sees that there is an “A” present already. Now, “A” executes “A”.compareTo(“A”), which results in 0. which means that element “A” is not inserted into the tree.

After all the insertions, using some tree traversal algorithm, the TreeSet data is printed onto the console. In this case, [A,K,Z].

The objects that we add to TreeSet must be homogeneous and comparable.

The problem with the above approach is that TreeSet was able to sort only in ascending order. so what if we want to sort in descending order? or what if there are Employee id’s and names with you and sort them in the alphabetical order of their names?

So, that’s when the Comparator interface comes into the picture!

Comparator Interface:

Comparator is mainly used for customized sorting. It is present in the java.util package. It has only 2 methods inside it, compare() and equals().

Overriding the compare() method when implementing the Comparator is mandatory.

Let’s see how it works in action with an example.

package com.example.helloworld;

import java.util.TreeSet;


public class HelloWorld{

public static void main(String[] args) {
TreeSet<String> t=new TreeSet<String>((str1,str2)->{
return str2.compareTo(str1);
});
t.add("Virat");
t.add("Dhoni");
t.add("Raina");
t.add("Jadeja");
System.out.println(t);//[Virat, Raina, Jadeja, Dhoni]
}

}

The above program shows how to sort names in descending order of their names.

Using Comparator we need not worry about the fact that TreeSet must contain only Homogeneous and Comparable, we can write our custom sorting logic for sorting elements, with full freedom.

Let’s conclude this article with an example that illustrates the above point.

//sort elements in increasing order of their lengths, if same length //sort based on alphabetical orderpackage com.example.helloworld;

import java.util.TreeSet;


public class HelloWorld{

public static void main(String[] args) {
TreeSet t=new TreeSet((obj1,obj2)->{
String str1=obj1.toString();
String str2=obj2.toString();
int len1=str1.length();
int len2=str2.length();
if(len1<len2)
return -1;
else if(len1>len2)
return 1;
else {
return str1.compareTo(str2);
}
});
t.add("A");
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("ABCD");
t.add("A");
System.out.println(t);//[A, AA, XX, ABC, ABCD]

}

}

That’s all for now on Comparator and Comparable interfaces, I’ll see you guys in the next one.

--

--