How to Sort Objects By Using Comparator in Java

Connect with

Oracle JavaThere are different approach to sort your custom object or List of Custom object in java. First of all, we have to understand what things we have to sort.

Let me classify broadly into two group,
1. natural ordering and
2. non-natural sorting ( complex sorting).

java.lang.Comparable interface is used to sort the object in natural order while java.util.Comparator interface is used to sort in any order either natural or non-natural. The sorting of list of any custom object in either natural order or non-natural order write your own comparator class either by anonymously or by name.

1. Use Case for Sorting

consider, on UI you have list view with few coloumns like name, date of birth, age. When load first time, it display sorting on name in ascending order. when you click second time on name it should display on descending order, when you click first time on dateOfBirth it should be ascending and when you click second time it should be on descending order.

Following are the business use case which you need to fulfill by using java.util.Comparator interface.

  • sorting of list of Employee objects on name in ascending order
  • sorting of list of Employee objects on name in descending order
  • sorting of list of Employee objects on dateOfBirth in ascending order
  • sorting of list of Employee objects on dateOfBirth in descending order

2. Why Sorting is required in Java?

Sorting is required in java for the following purpose.

  • if we have list of Custom object with populated values and we want to sort in-memory, it means don’t want to pull from db.
  • if we have already fetched list of objects from db and then want to sort in-memory to cater different use case to fulfill business requirement.

3. Comparator interface at a Glance

For Sorting of List of custom Java Object, you have to do following steps.

  1. Create your java POJO class
  2. write your Java.util.Comparator and defind sorting logic
  3. use Collections.sort(list, comparator),to sort the list

While implementing/overriding compare() method keep the following point in your mind. The compare() method compares two objects to each other, it should:

  1. Return a negative value if object1 is smaller than object2
  2. Return 0 (zero) if objec1 is equal to object2.
  3. Return a positive value if object1 is larger than object2.

4. Different ways of writing Comparator

there are different ways of writing your Comparator. You can write any one of the three different ways.

  1. Anonymous class of Comparator.
  2. java Class to implement Comparator
  3. java method which return java.util.Comparator

1. Anonymous class to sort dateOfBirth in ascending order


// anonymous comparator here provided in Collections.sort method
Collections.sort(list, new Comparator() {

  @Override
  public int compare(Employee emp1, Employee emp2) {
	if (emp1.getDateOfBirth().before(emp2.getDateOfBirth())) {
	 return -1;
	} else if (emp1.getDateOfBirth().after(emp2.getDateOfBirth())) {
	  return 1;
	} else {
	  return 0;
	}
  }

});

2. Java Class to sort dateOfBirth property in ascending order


package com.mysoftkey.collection;

import java.util.Comparator;

/**
 * @author ranjeet Jha
 *
 */
public class DateOfBirthAscendingComparator implements Comparator{

 @Override
 public int compare(Employee emp1, Employee emp2) {
   if ( emp1.getDateOfBirth().before(emp2.getDateOfBirth()))  {
	return -1;
   } else if ( emp1.getDateOfBirth().after(emp2.getDateOfBirth())) {
	return 1;
   } else {
	return 0;
   }
 }

}

3. Method which returns Compartor object

/**
 * it return DateOfComparator instance which implements in ascending order.
 * 
 * @return
 */
public static Comparator getDateOfBirthComparator() {
   Comparator employeeCompartor = new Comparator() {

    @Override
    public int compare(Employee emp1, Employee emp2) {
	if (emp1.getDateOfBirth().before(emp2.getDateOfBirth())) {
		return -1;
	} else if (emp1.getDateOfBirth().after(emp2.getDateOfBirth())) {
		return 1;
	} else {
		return 0;
	}
     }
  };

  return employeeCompartor;
}

4. Sorting list of Java Objects using Comparator

Following are the steps to sort Employee objects, on dateOfBirth in ascending order as:

Employee.java

/**
 * 
 */
package com.mysoftkey.collection;

import java.util.Date;

/**
 * domain model class to hold employee property.
 * 
 * @author Ranjeet Jha
 *
 */
public class Employee {

	private String name;
	private Date dateOfBirth;
	
	public Employee (String name, Date dob) {
		this.name = name;
		this.dateOfBirth = dob;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public Date getDateOfBirth() {
		return dateOfBirth;
	}
	
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

}

SortingByComparatorExample.java

package com.mysoftkey.collection;

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

/**
 * java program to sort list of custom object i.e. Employee object
 * which can be sort either in ascending order.
 * 
 * @author ranjeet jha
 *
 */
public class SortingByComparatorExample {
 /**
  * @param args
  */
 public static void main(String[] args) {

	List list = new ArrayList();

	Calendar cal = Calendar.getInstance();
	cal.add(Calendar.YEAR, -20);
	cal.add(Calendar.MONTH, -2);

	list.add(new Employee("Ranjeet", cal.getTime()));

	cal.add(Calendar.YEAR, 3); // add 3 years in current year.
	list.add(new Employee("David", cal.getTime()));
	cal.add(Calendar.YEAR, -6);
	list.add(new Employee("Joe", cal.getTime()));

	System.out.println("---------- Before Sorting, values as: ------------ ");
	for (Employee e : list) {
    	  System.out.println("name : " + e.getName() + " , dateOfBirth: " + e.getDateOfBirth());
	}

	// anonymous comparator here provided in Collections.sort
	Collections.sort(list, new Comparator() {

	  @Override
	  public int compare(Employee emp1, Employee emp2) {
	    if (emp1.getDateOfBirth().before(emp2.getDateOfBirth())) {
	      return -1;
	    } else if (emp1.getDateOfBirth().after(emp2.getDateOfBirth())) {
	     return 1;
	   } else {
	    return 0;
	   }
         }

	});

	System.out.println("----- After Sorting on dateOfBirth property in Ascending order as: --- ");
	for (Employee e : list) {
	 System.out.println("name : " + e.getName() + " , dateOfBirth: " + e.getDateOfBirth());
	}

	/*Collections.sort(list, getNameDescComparator());
	System.out.println("------ After Sorting on name property in descending order as: --- ");
	for (Employee e : list) {
	 System.out.println("name : " + e.getName() + " , dateOfBirth: " + e.getDateOfBirth());
	}*/

	}

	/**
	 * it return DateOfComparator instance which implements in ascending order.
	 * 
	 * @return
	 */
	public static Comparator getDateOfBirthComparator() {
	  Comparator employeeCompartor = new Comparator() {

	 @Override
	public int compare(Employee emp1, Employee emp2) {
	 if (emp1.getDateOfBirth().before(emp2.getDateOfBirth())) {
	   return -1;
	  } else if (emp1.getDateOfBirth().after(emp2.getDateOfBirth())) {
	   return 1;
	  } else {
	    return 0;
	  }
	}

	};

	return employeeCompartor;
     }
	
}

Console Output of program:

---------- Before Sorting, values as: ------------ 
name : Ranjeet , dateOfBirth: Fri Oct 25 17:01:32 IST 1996
name : David , dateOfBirth: Mon Oct 25 17:01:32 IST 1999
name : Joe , dateOfBirth: Mon Oct 25 17:01:32 IST 1993
----- After Sorting on dateOfBirth property in Ascending order as: --- 
name : Joe , dateOfBirth: Mon Oct 25 17:01:32 IST 1993
name : Ranjeet , dateOfBirth: Fri Oct 25 17:01:32 IST 1996
name : David , dateOfBirth: Mon Oct 25 17:01:32 IST 1999

4. Sorting on Name Property

For sorting on name property in descending order, you can write your own Comparator logic by any of the three ways. anonymous class, named class, method which return comparator object.

Method which return Comparator object

/**
 * it return nameDescComparatpr instance which implements in descending order.
 * 
 * @return
 */
public static Comparator getNameDescComparator() {
  Comparator employeeCompartor = new Comparator() {

	@Override
	public int compare(Employee emp1, Employee emp2) {
  	  if (emp1.getName().compareTo(emp2.getName()) > 1) {
		return -1;
	} else if (emp1.getName().compareTo(emp2.getName()) < 0) {
		return 1;
	} else {
	       return 0;
	}
    }

};

return employeeCompartor;
}
 Collections.sort(list, getNameDescComparator());

 System.out.println("------ After Sorting on name property in descending order as: --- ");
 for (Employee e : list) {
  System.out.println("name : " + e.getName() + " , dateOfBirth: " + e.getDateOfBirth());
 }

Console Output of program:

------ After Sorting on name property in descending order as: --- 
name : Ranjeet , dateOfBirth: Fri Oct 25 17:01:32 IST 1996
name : Joe , dateOfBirth: Mon Oct 25 17:01:32 IST 1993
name : David , dateOfBirth: Mon Oct 25 17:01:32 IST 1999

Sorting by reverse order:
for sorting to reverse order either you can write your comparator or use Collections.reverse() method to reverse

// after Collection.sort(list, comparator), place following code to reverse the list
Collections.reverse(list);

There is no restriction of implementing java.util.Comparator interface in your POJO class for sorting any property in any order using java.util.Comparator interface. You can visit my another post: How to sort list of Java Objects by using Comparable.

If you want to reverse the sorted list , it means you have sorted in ascending order and now you want to sort in reverse i.e. descending order then use Collections.reverse(list);.


Connect with

1 thought on “How to Sort Objects By Using Comparator in Java

  1. Pingback: sweta

Leave a Reply

Your email address will not be published. Required fields are marked *