How To Sort Java Object Using Comparable And Comparator?

This tutorial shows how to use java.util.Comparator and java.lang.Comparable to sort a Java object based on its property value. Here I have created Employee object with Name and Age properties, we will be able to sort the list of objects based on the values in the property’ Lets look at the example.


import java.util.Comparator;

class Employee implements Comparator<Employee>, Comparable<Employee>{
   private String empName;
   private int empAge;

   Employee(String name, int age){
      empName = name;
      empAge = age;

   public String getEmpName(){
      return empName;

   public int getEmpAge(){
      return empAge;

   // Overriding the compareTo method
   public int compareTo(Employee e){
      return (this.empName).compareTo(e.empName);

   // Overriding the compare method to sort the age
   public int compare(Employee e, Employee e1){
      return e.empAge - e1.empAge;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorExample{

   public static void main(String args[]){
      // Takes a list of Employee objects
      List<Employee> empList = new ArrayList<Employee>();

      empList.add(new Employee("Zaheer",30));
      empList.add(new Employee("Ashwin",25));
      empList.add(new Employee("Karnan",31));

      // Sorts the array list

      //displays the sorted list of names
      for(Employee a: empList)
         System.out.print(a.getEmpName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(empList, new Employee());
      System.out.println(" ");
      //displays the sorted list of ages
      for(Employee a: empList)
         System.out.print(a.getEmpName() +"  : "+
		 a.getEmpAge() + ", ");

Output for the above example will be:

Ashwin, Karnan, Zaheer,
Ashwin  : 25, Zaheer  : 30, Karnan  : 31,



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind