Do you know what are the differences between the “Comparable vs Comparator in Java“? Well, do you have any idea about how Comparators work, how Comparable works?
So, if youโre interested in getting help with Java homework and curious to know the difference between Comparable and Comparator in Java then this article is for you.
Let us know some interesting facts while learning about the Comparable vs Comparator in Java. In this article, we will try to clarify the concept related to Comparable vs Comparator Java. Also, along with that, we will try to implement Comparable.
So, why do we use comparable and comparator interface in Java? Well, both of these interfaces are used to implement sorting. Each interface has its own properties and can be used as per the requirements of the code.
Let us learn more about comparable and comparator interfaces in detail. Let us dive in!
Summary of the Article:
- In this article, we will cover all about a comparable and comparator in Java and see how both of these are designed to work.
- There are two kinds of interfaces in Java that are used for sorting: The Comparable Interface and The Comparator Interface.
- In Java, both comparable and comparator work to sort objects in the Java class.ย
- Deciding what to use between comparable vs comparator for your code depends upon the kind of action you want your code to make.
- A comparable object can compare itself to some other object. However, using comparators to sort objects, helps us to consider multiple options at the same time that are external to the class.
Before we start making the differences between Comparable vs Comparator in Java, let us first know about them briefly.ย
What Is A Comparable? Read Below
In Java, you can perform sorting with the help of two different interfaces. One of them is the comparable interface. The Java comparable interface allows us to sort the data into different data types. Whenever we need to compare a set of data members or an object by any of the data members, we can use the Java Comparable interface.
The Comparable interface is like your friend who can sort any one item at a given time. Comparable can be used to sort the lists of elements by using any one item. It is a very easy sorting interface.ย
Comparable uses the compareTo() method. It is the same method that we used to compare two strings in Java. If youโre not aware of comparing strings in Java, then you can check out our article. Also, in this case, while sorting it modifies the original class elements. That may create problems at some point in time.
Many developers used it for sorting such cases. But it has one drawback, it canโt
sort the list by the many data types at the same time. For that purpose, we need to take the help of a Comparator interface.ย
Also, if you want to know more about algorithms then you can check out our article on โQuick Sort Algorithmโ to have more knowledge about the same.
How To Do Implementation Of Comparable In Java?
It is time to know how comparable works. As discussed above, we know that the comparable interface uses the compareTo() method. To know how it works, we have to implement a Comparable code.ย
To implement the comparable interface, we need the java.lang.Comparable interface. We have to develop two important parts there.
- Declaration Of Comparable Class: Here, we need to declare a class that will act as the Comparable. Here, we need to provide the fields. We can add different fields of different data types. Here we have added two fields. One is the Id which takes an integer value. Another is Name which takes a string value. The values that will be provided by the user will be stored here.ย
- Comparing The Field: Now, we need to compare the lists by a certain object or data member. Here, we have taken Id for comparing purposes. If the certain ID is greater than the first one, it will return 1. Otherwise, if it is smaller then it will return the -1. In this way, we have to compare the items. Also, based on the operation sorting will be completed.
Let us now have a look at the code implementation of the comparable interface.
import java.util.*;
import java.io.*;
// Declaration Of Comparable Class
class experiment implements Comparable{
// Declaring The Fields
int id;
String name;
experiment(int id,String name){
this.id=id;
this.name=name;
}
// Class To Compare Between The Inputs Based On The Ids
public int compareTo(experiment ex){
if(id==ex.id)
return 0;
else if(id>ex.id)
return 1;
else
return -1;
}
}
//Creating a test class to sort the elements
public class Main{
public static void main(String args[]){
// Declaring The Array List
ArrayList zap=new ArrayList();
// Adding Values To Array List
zap.add(new experiment(11,"CodingZap"));
zap.add(new experiment(10,"ZapOne"));
zap.add(new experiment(15,"Java"));
// Method To Sort
Collections.sort(zap);
// Printing The Vallues Using The For Each Loop
for(experiment ex:zap){
System.out.println(ex.id+" "+ex.name);
}
}
}
As seen in the above output, the strings or collection is sorted in the ascending order or the default order. In case we need a custom order to sort arrays, objects, or other wrapper class objects, then we can make use of the comparator interface.
Let us learn about the comparator interface and see how custom sorting order is implemented. Read further to know!
What Is A Comparator? Read Below
The Comparator interface is another sorting interface in Java. It is also used for the same purpose as the comparable interface, that is, to sort the list of elements or objects. The comparator sorts the elements by the different types of data types at the same time. It takes a small amount of time to complete the process.
It is quite difficult compared to the Comparable method. it uses the compare() method. This method is difficult to implement. Also, it doesnโt change the original class elements there.
How To Do Implementation Of Comparator In Java?
Now, it is time to know how Comparators work. In this case, we need to first develop the Comparator class. The implementation of the Comparator class will be the same as for the Comparable class.ย ย
In this case, we will use java.util.Comparator interface to sort the objects based on multiple attributes or criteria. Also, the compareTo() method will be used in this case as well.ย
Here, the Comparator can sort the list by many fields at the same time. Here, we have to sort the list by the ID & the Name field.
- Comparing The Field By Id: Here the logic is the same as for the Comparable. But, we have to consider the values of both entities. Then we have to compare it. If the first ID is greater than the second one, it will return 1. Otherwise, if it is smaller than a second will return the -1. In this way, we have to compare the items. Also, based on the operation sorting will be completed.
- Comparing The Field By Name: In this case, we have to compare two names. Then we have to sort it out. As the names are the strings, we can use the compareTo() method. We have already seen the use of this method in the article comparing two strings in Java. It will compare and the return value can be some arbitrary value. Based on it, names will be sorted in ascending order.ย
Have a look at the program below to see how the implementation of the comparator interface is done.ย
import java.util.*;
import java.io.*;
// Declaration Of Class Experiment
class experiment{
// Adding The Fields
int id;
String name;
experiment(int id,String name){
this.id=id;
this.name=name;
}
}
// Program For Id Comparator
class IdComparator implements Comparator{
public int compare(experiment s1,experiment s2){
if(s1.id==s2.id)
return 0;
else if(s1.id>s2.id)
return 1;
else
return -1;
}
}
// Class For Name Comparator
class NameComparator implements Comparator{
public int compare(experiment s1,experiment s2){
return s1.name.compareTo(s2.name);
}
}
class Main{
public static void main(String args[]){
// Creating A List Of Elements
ArrayList zap=new ArrayList();
zap.add(new experiment(10,"ZapOne"));
zap.add(new experiment(11,"CodingZap"));
zap.add(new experiment(15,"Java"));
System.out.println("Sorting by Ids");
//Using NameComparator to sort the elements
Collections.sort(zap,new IdComparator());
//Traversing the elements of list
for(experiment st: zap){
System.out.println(st.id+" "+st.name);
}
System.out.println();
System.out.println("Sorting by Names");
//Using NameComparator to sort the elements
Collections.sort(zap,new NameComparator());
//Traversing the elements of list
for(experiment st: zap){
System.out.println(st.name+" "+st.id);
}
}
}
Output:
From the above output, we can clearly see that we have performed sorting based on multiple criteria- IDs and Names. In both cases, the results are printed in the ascending order.
Are you now wondering, what can be cases in which you can use comparable and comparator to sort objects in your program? Well then, let us see where both of these interfaces are used.
When To Use Comparable and Comparator In Your Java Code?
The use of the comparable interface and the comparator interface depends upon the requirements of your code or sorting logic. Below are some of the cases that tell us where to use comparable and comparator in Java. Let us have a look!
Use of Comparable Interface
- You can use the comparable interface when you want to establish a natural sorting order or default sorting order for the objects based on their intrinsic properties. For example, a list of dates in a class may be sorted in chronological order using the comparable object.ย
- ย The comparable interface in Java is used in cases where you require a single criteria or attribute to sort objects.
- The comparable interface is suitable when the sorting sequence logic is linked closely to the particular class.
Use of Comparator Interface
- The comparator interface can be used when we need to perform custom sorting logic on an object.
- Here, you can have multiple criteria or attributes to sort objects. For example, sorting of an employee can be done based on their name, department, and branch.ย
- The comparator interface is complex to implement but provides flexibility as you can have external properties or classes while sorting the contents or objects.ย
We have gained some knowledge about Comparable & Comparator. Now, it is time to get some more knowledge by making a table of differences between Comparable vs Comparator.
Let us develop the table & acquire some more knowledge from it.
What Is The Differences Between The Comparable Vs Comparator?
Comparable In Java | Comparator In Java |
It can sort the list with the help of only one field at the same time. | Comparator can sort the list with the help of many fields at the same time. |
It changes the original class elements. The actual class is being modified here. | It doesnโt change the original class. The actual class remains the same as earlier. |
Java.lang package should be used to implement Comparable. | Java.utill package should be used to implement Comparator. |
It uses the compareTo() method to compare two fields & sort them. | It uses the compare() method to compare two fields & sort them. |
General Syntax: Collections.sort(listname); | General Syntax: Collections.sort(listname, comparator) |
Some Real-World Applications of Comparable and Comparator
So far, we have gotten to know what are comparable and comparator interfaces in Java and how can we implement them. We have also differentiated between both of these interfaces above.ย
Let us now look at some real-world applications of comparable and comparators. Letโs have a look at the below points.
- Sorting objects in collections: Both comparable and comparators help us to sort objects in collections like ArrayList, LinkedList, TreeSet, and TreeMap.
- Database operations: These interfaces help to sort the results of a query based on different or custom criteria.
- Web Applications: Comparable and Comparator interfaces help to sort data extracted or retrieved by APIs or Databases before displaying on the web pages.
- Machine Learning and Data Science: The comparable and comparator help in data preprocessing and organization for training the model.
Conclusion:
As we saw differences between Comparable vs Comparator are very important.
We have to clear the basics of the Java programming language to understand the concept in a good manner.
As per the choice of the individual, they can use any method mentioned above. It is a very useful implementation.
So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.
Takeaways:
- Java Programming offers us two types of interfaces to sort objects in collections or wrapper classes. These interfaces are called comparable and comparator.ย
- A comparable interface is used in the natural ordering of objects and is used when we need to sort data based on the intrinsic properties of the objects present in a class.
- A Comparator interface, on the other hand, is used when we need to perform custom ordering of objects and sort data based on external sorting logic.ย
- Comparable uses a single criteria to sort objects, whereas, Comparator uses multiple sorting criteria to sort objects.ย
- Both of these interfaces see their uses in a variety of real-world applications.