How to Sort List of Objects Using Comparable in Java?

Connect with

How to Sort List of Objects By Using Comparable in JavaLearn how to sort list of objects using comparable in Java, step by step example of sorting using comaprable, why sorting required, use case of sorting, etc.

1. Overview of sorting in Java

There are different approaches to sort your custom object or List of the given custom object in java. First of all, we have to understand, what we have to sort, sorting for which property of a custom object, which orders either ascending order or descending order. Sorting classified into two groups broadly: first natural ordering and second, non-natural sorting ( complex sorting). java.lang.Comparable interface is used to sort the object in a natural order. The sorting of the natural order is very simple by implementing a Comparable interface on one property of a custom object.

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

3. Why Sorting is required in Java?

Sorting of list of object in java is required 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. How to sort list of objects using Comparable in Java?

Following are the step-by-step example to sort list of objects using comparable in Java 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.
	 */
	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 the first object is greater than the second.
        // return 0, if the first object is equal to the second.
        // return NEGATIVE, if the 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());
	}
 }

}

5. Console Output of sorting example

Following are the console output of sorting java examples.

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

6. 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:
output to sort list of object using comparable, here property are

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

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

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 Posts

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

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

  1. Pingback: Neeraj

Leave a Comment

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