Collections can be sorted by using Comparable or by Comparator interface. In this article we will see how to sort java object based on various values.

List can be sorted by following:

  • Collections.sort(l)
  • Collections.sort(l,<comparator>)

If List consists of String elements, it will be sorted into aphabetical order. If List consists of Date elements, it will be sorted in chronological order. This happens because String and Date implement Comparable interface. Comparable implementation provide a natural ordering for a class, which allows objects of that class to be sorted automatically. Byte, Character, Long, Integer, Short, Double, Float, BigInteger, BigDecimal, Boolean, File, String, Date and CollationKey implement Comparable.

If we try to sort a list that have elements that don’t implement comparable then we get ClassCastException

Comparable interface

Comparable interface has compareTo() method that has to be implemented for sorting an object.

Example1: Sort by rank of an Employee

Let’s create a data object Employee that implements Comparable. This object is created to sort based on rank attribute. rank attribute is an Integer and already implements Comparable, so we can use compareTo() method on it to compare ranks. compareTo() returns negative integer, zero or positive integer based on receiving object is less than,equal to or greater than specified Object.

Employee – Data Object

This is a data object for employee details.

Employee Sort

This is the class where we test sort. Collections.sort(<List<?>>) is used to sort the list.

Output

Comparator

If we want to sort objects in an order other than natural ordering or if we want to sort objects that don’t implement comparable, we will have to provide a Comparator.(Comparable has some rules that have to be followed, these restrictions might be reason why object don’t implement comparable)

Example: Sort by performanceRating of an Employee in above scenario

This is continuation of above scenario. Employee object has already have code for using sorting by rank using comparable. Now if you want to sort by performance then you can use comparator.

Add code to EmployeeSort

We need to include a Comparator class that has compare() that compares performanceRating between two Employee objects. performanceRating attribute is an Integer and already implements Comparable, so we can use compareTo() method on it to compare performanceRating.

Output

Learn and Share