How to Sort Objects Using Comparator in Java

Connect with

How to Sort Objects Using Comparator in JavaLearn how to sort objects using comparator in Java. Example of sorting on Java.util.Date, String, integer property on asc and desc order. There are different approach to sort a list of object or List of Custom object in java.

1. Overviewo of sort objects using comparator in Java

Let me classify broadly into two group of sorting on any property of a list of custom java objects either in ascending or descending order.

  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 ascending order or descening order , write your own comparator class either by anonymously or by name.

2. Use Case for Sorting

For instance, you have a list view UI, a few columns like name, date of birth, age. When loading the first time, it displays sorting on the name in ascending order. when you click a second time on the name heading, it should display in descending order, when you click a first time on dateOfBirth heading, it should be in ascending order of dateOfBirth hand when you click the second time it should be in descending order of dateOfBirth.

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

3. 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.

4. 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.

5. Different ways of writing Comparator for sorting

There are different ways of writing your Comparator class for sorting of custom objects. 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

5.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;
	}
  }

});

5.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;
   }
 }

}

5.3. Method which returns Compartor object

/**
 * it returns 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;
}

6. Sorting list of Object 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 to hold employee property for sorting of the list.
 */
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 returns 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 sorting example using comparator

---------- 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

7. 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, a method which returns comparator object.

Method which return Comparator object

/**
 * it returns 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);.

8. Related Sorting Post

By the way, if you have not visted other sorting posts, you must visit following:

10. Reference

I hope you enjoyed this post of how to sort objects using comparator in java, and you can visit core Java tutorial for more blog post.

Visit Oracle Java docs.

Happy learning! 🙂


Connect with

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

  1. Pingback: sweta

Leave a Comment

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