Comparable and Comparator in Java with Example

Comparable and Comparator in Java with Example thumbnail
9K
By Dhiraj 22 January, 2017

In Java when it comes to sort any collections,comparable and comparator comes into picture.Comparable and Comparator are two interfaces provided by Java Core API.Here we will take a look into why Comparable and Comparator are used for sorting though there are inbuilt methods provide by Java API to sort primitive types array or Wrapper classes array or list.What are the use cases to choose Comparable for sorting and in which scenario Comparator should be preferred.Now, let's see how to use Comparator and Comparable in Java with example.

Comparable Interface

The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort the Lists and arrays of objects respectively.At first, let's quickly look into a simple example and will discuss more about it.

Here the Employee class implements Comparable and overrides it's compareTo() method to sort the employee object based on it's name.

public class Employee implements Comparable<Employee>{
	
	private String name;
	private String deptName;
	private String address;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	//overriding compareTo() method
	@Override
	public int compareTo(Employee o) {
		return name.compareTo(o.getName());
	}

}

Now if you have a collection of employee objects then it can be used as below for sorting:

//populate the employeeList by dummy records or get from DB
List<Employee> employeeList = new ArrayList<Employee>();

//Sort the emplyeeList by it's name in ascending order
Collections.sort(employeeList);

Now what if we want to sort Employee collection based on age.Since we sorted our ArrayList by implementing compareTo() method, we seem to stuck. We can only implement compareTo() once in a class, so how to sort the list again by some other attributes.This is the use case where we require Comparator interface.

 Other Interesting Posts
Hello World Java Program Breakup
Serialization and Deserialization in Java with Example
Convert HashMap to List in Java
Sorting HashMap by Key and Value in Java
Why wait(),notify(),notifyAll() defined in object class in Java

Comparator Interface

The Comparator interface gives us the capability to sort a given collection any number of different ways.The other important capability is that we can use it to sort instances of those classes which we can't modify, unlike the Comparable interface, which forces to change the source code of class which we want to sort.Let us take a quick example.

public class Employee {
	
	private String name;
	private String deptName;
	private String address;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	//Sort employee by name
	public static class NameSort implements Comparator<Employee> {

		@Override
		public int compare(Employee o1, Employee o2) {
			return o1.getName().compareTo(o2.getName());
		}
		
	}
	
	//sort employee by deptName
	public static class DeptNameSort implements Comparator<Employee> {

		@Override
		public int compare(Employee o1, Employee o2) {
			return o1.getDeptName().compareTo(o2.getDeptName());
		}
		
	}

}

To sort the collection of employee :

//populate the employeeList by dummy records or get from DB
List<Employee> employeeList = new ArrayList<Employee>();

//Sort employeeList by employee name
Collections.sort(employeeList, new Employee.NameSort());

//Sort employeeList by dept name
Collections.sort(employeeList, new Employee.DeptNameSort());

Points to Remember

1. In case of Comparable sorting logic must be in same class whose objects are being sorted.Hence, restricts to sort a given collection by single attribute.Whereas, in case of Comparator, sorting logic is defined in seperate class.Hence, we can write different sorting based on different attributes of objects to be sorted.

2. Class whose objects to be sorted must implement Comparable interface.In case of Comparator, class whose objects to be sorted do not need to implement this interface.

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Core Java