How to Sort List of Objects By Using Comparable 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 we are trying to sort. Let me classify in two group broadly, first natural ordering and second, non-natural sorting ( complex sorting). java.lang.Comparable interface is used to sort the object in natural order. The sorting of natural order is very simple by implementing Comparable interface.

1. Use Case of Natural sorting by using Comparable

  • sorting of list of Person Object on name in ascending order
  • sorting of list of Person Object on name in ascending order
  • sorting of list of Person Object on age in ascending order
  • sorting of list of Person Object on age in ascending 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. How to sort list of Java Objects?

Following are the list of steps to sort Person objects, on name in ascending order as:

Person.java


package com.mysoftkey.collection;

/**
 * Java POJO to hold property of Person entity.
 * for simplicity I kept only three property.
 * 
 * @author ranjeet.kr@gmail.com
 *
 */
public class Person implements Comparable{

        private int id;
        private int age;
	private String name;
	
	/**
	 * Constructor to populate values.
	 * 
	 * @param id
	 * @param age
	 * @param name
	 */
	public Person(int id, int age, String name) {
		this.id = id;
		this.age = age;
		this.name = name;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int compareTo(Person person) {
		
	// return POSITIVE , if first object is greater than the second.
        // return 0 , if first object is equal to the second.
        // return NEGATIVE , if first object is less than the second one.
	 return this.name.compareTo(person.getName());
	 
	}
	
	@Override
	public String toString() {
		return "id: " + id + " , name: " + name +" , age: " + age;
	}
}

SortingPersonComaparableExample.java

package com.mysoftkey.collection;

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

/**
 * this java class is for sorting of Person 
 * in natural order by using Comparable interface.
 * 
 * @author ranjeet.kr@gmail.com
 *
 */
public class SortingPersonComaparableExample {

 /**
  * @param args
  */
  public static void main(String[] args) {
		
	List list = new ArrayList();
		
	//Populating values in Person Object via constructore
	// and adding Person Object in list 
	list.add(new Person(1, 20, "Ranjeet"));
	list.add(new Person(2, 40, "Bob"));
	list.add(new Person(3, 30, "Mark"));

	System.out.println("---------- Before Sorting, values as: ------------ ");
	for (Person p : list) {
	 System.out.println("id: " + p.getId() + " , name: " + p.getName() +" , age: "+ p.getAge());
	}
		
	// Sorting of List objects ,
	Collections.sort(list);
		
	System.out.println("---------- After Sorting on name property in Ascending order as: ------------ ");
	for (Person p : list) {
	  System.out.println("id: " + p.getId() + " , name: " + p.getName() +" , age: "+ p.getAge());
	}
 }

}

Console Output of program:

---------- Before Sorting, values as: ------------ 
id: 1 , name: Ranjeet , age: 20
id: 2 , name: Bob , age: 40
id: 3 , name: Mark , age: 30
---------- After Sorting on name property in Ascending order as: ------------ 
id: 2 , name: Bob , age: 40
id: 3 , name: Mark , age: 30
id: 1 , name: Ranjeet , age: 20

4. Sorting on Age Property

For sorting on age property in Ascending order, you have to place following java code in Person.java for overriding compareTo() method

@Override
public int compareTo(Person person) {
	
// return POSITIVE , if first object is greater than the second.
// return 0 , if first object is equal to the second.
// return NEGATIVE , if first object is less than the second one.
 return (this.age - person.getAge());
}

Console Output of program:

---------- Before Sorting, values as: ------------ 
id: 1 , name: Ranjeet , age: 20
id: 2 , name: Bob , age: 40
id: 3 , name: Mark , age: 30
---------- After Sorting on name property in Ascending order as: ------------ 
id: 1 , name: Ranjeet , age: 20
id: 3 , name: Mark , age: 30
id: 2 , name: Bob , age: 40

Sorting by reverse order:

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

Console Output of program to sort on age in descending order:

---------- Before Sorting, values as: ------------ 
id: 1 , name: Ranjeet , age: 20
id: 2 , name: Bob , age: 40
id: 3 , name: Mark , age: 30
---------- After Sorting on age property in descending order as: ------------ 
id: 2 , name: Bob , age: 40
id: 3 , name: Mark , age: 30
id: 1 , name: Ranjeet , age: 20

5. Comparable 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. implements Java.lang.Comparable interface in POJO class
  3. override compareTo() method in POJO
  4. use Collections.sort(list),to sort the list

There is a restriction of sorting by using java.lang.Comparable interface. You can think and ask yourself, what is the restriction? Think this way , if you have to sort on multiple properties in same POJO java class for example on name in ascending and on age in descending etc. You have to use java.util.Comparator interface for sorting. You can visit my next post: How to sort list of Java Objects by using java.util.Comparator.

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 List of Objects By Using Comparable in Java?

  1. Pingback: Neeraj

Leave a Reply

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