What is Comparable and Comparator in java?

(Last Updated On: February 26, 2019)

Comparable and comparator in java with examples and explanation for when to use comparator interface and comparable interfaces in java programs. After reading the answer, you will be able to clearly understand comparable and comparator interface and why and when you should choose each one.

Answer:

The comparable and comparator interface in java programming is used to compare and sort objects of a class. Let’s understand with simple example. We have user defined employee class with fields name, age and salary. We may want to sort employees based on salary or may want to sort it based on age, then we can use comparable or comparator interface for sorting employees.

Now the question is what interface between comparable and comparator we should choose to implement and when. But, first let’s understand each one with program example.

Comparable interface in Java:

If we want to sort objects using comparable interface, then the class must implement it. It contains public int compareTo(Object o) method that a class will implement. for example, in below program class Employee will implement it.

 

Comparable Interface Example in Java

public class Employee implements Comparable {

	int age;
	int salary;
	String name;

	public Employee(String name, int age, int salary) {
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public int getAge() {
		return this.age;

	}

	public int getSalary() {
		return this.salary;

	}

	public String getName() {
		return this.name;

	}

	public String toString() {
		return this.name + " " + this.age + " " + this.salary;
	}
	
	
	@Override
	public int compareTo(Employee o) {
		
		 return this.getAge() - o.getAge();
		
	}

	
}

 

Here is the test class for comparable interface example.

public class ComparableExample {

	public static void main(String[] args) {
		
		ArrayList emplist = new ArrayList();
		//Create multiple employees objects
		
		Employee e1 = new Employee("Bob",32, 20000);
		Employee e2 = new Employee("John",25, 30000);
		Employee e3 = new Employee("Lisa",19, 15000);
		Employee e4 = new Employee("Peter",60, 50000);
		
		//Add employees into a list in which employee
		//objects will be sorted
		emplist.add(e1);
		emplist.add(e2);
		emplist.add(e3);
		emplist.add(e4);
       
		//Just pass the employee list
		//Collection sort will use compareTo(Employee o)
		//method from this class itself
		Collections.sort(emplist);
		
		//display sorted result
		 System.out.println("Sorted by Age");
		 for(Employee emp:emplist){
			 System.out.println(emp.toString());
		 }	      
		
	}

}

 

Output:

Sorted by Age
Lisa 19 15000
John 25 30000
Bob 32 20000
Peter 60 50000

 

Comparator interface in Java:

Comparator interface contains two methods compare (Object obj1, Object obj2) and equals (Object element). We can implement both or compare method only in custom comparators.

We create a user defined comparator class and implement comparator interface. Note that multiple separate comparator class can be created. For example, we can write 2 comparators for employee class i.e. one comparator for based on Age of the employee and another one based on salary e.g. AgeComparator and SalaryComparator and apply anyone wherever required.

Once we have created comparator class then it can be applied explicitly to collections java sort method i.e. Collections.sort() method constructor for sorting. Below is the object sorting example using comparator classes.

Here is a age comparator that will sort objects based on age.

 

package comparator;
import java.util.Comparator;

public class AgeComparator implements Comparator {

	@Override
	public int compare(Employee e1, Employee e2) {
		
		//Sort in ascending order
		 return e1.getAge() - e2.getAge();
		
	}

}

 

Here is a salary comparator class that will sort objects based on employee salary.

 

package comparator;
import java.util.Comparator;

public class SalaryComparator implements Comparator {

	@Override
	public int compare(Employee e1, Employee e2){
		
		//Sort in ascending order
		 return e1.getSalary() - e2.getSalary();
		
	}
}

Here is employee object on we will apply comparators and sort its object accordingly.

package comparator;

public class Employee {

	int age;
	int salary;
	String name;

	public Employee(String name, int age, int salary) {
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public int getAge() {
		return this.age;

	}

	public int getSalary() {
		return this.salary;

	}

	public String getName() {
		return this.name;

	}

	public String toString() {
		return this.name + " " + this.age + " " + this.salary;
	}
}

 

Test class using comparator interface example for sorting based on age. To sort employee objects based on salary, the same way it can be applied

package comparator;
import comparator.Employee;
import java.util.ArrayList;
import java.util.Collections;


public class ComparatorClient {

	public static void main(String[] args) {
		
		ArrayList emplist = new ArrayList();
		//Create multiple employees objects
		
		Employee e1 = new Employee("Bob",32, 20000);
		Employee e2 = new Employee("John",25, 30000);
		Employee e3 = new Employee("Lisa",19, 15000);
		Employee e4 = new Employee("Peter",60, 50000);
		
		//Add employees into a list in which employee
		//objects will be sorted
		emplist.add(e1);
		emplist.add(e2);
		emplist.add(e3);
		emplist.add(e4);
       
		//Crate respective comparator object on what employee
		//fields we want to sort.
		
		//Lets sort employees based on age
		AgeComparator ageComparator = new AgeComparator();
		//Now use collection.sort() method to sort objects.
		// and pass custom comparator that we create
		//on what ever filed we want to sort.
		//Using Age comparator or salary comparator
		Collections.sort(emplist, ageComparator);
		
		//display sorted result		
		 System.out.println("Sorted by Age");
		 for(Employee emp:emplist){
			 System.out.println(emp.toString());
		 }
	       
		
	}

}

 

Output:

Sorted by Age
Lisa 19 15000
John 25 30000
Bob 32 20000
Peter 60 50000

 

When to choose comparable and comparator interface in java programming?

Hope you have understand the difference between these interfaces by reading example. However, here is to focus

If we have a fixed requirement that class objects will be sorted based on a single field of the class, and expect that in future this requirement will not be change then it is better to use comparable interface. If we have requirement in software projects that class objects can be sorted using multiple fields then use multiple comparator class and use it explicitly.

This is the flexibly a comparator class gives that we can create multiple comparator classes and use it over objects. Where comparable interface is fixed.

We have used comparable interface in above class based on age, but, if we want to make it based on salary, then we need to modify employee class then. Whereas, we don’t need to modify in case of comparator class.
Read more on differences and advantages of comparator over comparable in java programming.
NOTE:

In in compare() or compareTo() method of interfaces we write custom comparison code. We can write java code for ascending order sorting or descending order or any custom based on requirement. In above, comparison code is for ascending order sorting.