How to Sort ArrayList of Objects in Java

In this tutorial you will learn how to sort arraylist of objects in java.

In our previous tutorial we have seen how to sort arraylist of String or Integer type using Collection.sort() method.

Can we use that process to sort an arraylist of custom objects? The answer is big no.

For doing this we have to use Comparable or Comparator interfaces.

Below I have shared an example for each of them.

Sort ArrayList of Objects Using Comparable

Comparable is used to sort an arraylist of object on the basis of single property at a time.

For example we have student data in which we have two properties, name and age. We can sort it by name or age.

This can be done by implementing Comparable interface and overriding its compareTo() method.

 

Student.java

 

SortObjectArrayList.java

 

Output

Name:Neeraj, Age:22
Name:Pankaj, Age:25
Name:Pawan, Age:27
Name:Suraj, Age:28

 

Sort ArrayList of Objects Using Comparator

We can sort student data on the basis of multiple properties like name and age by overriding compare() method of Comparator interface.

 

Student.class

 

SortObjectArrayList.java

 

Output

Sort by Name:
Name:Neeraj, Age:22
Name:Pankaj, Age:25
Name:Pawan, Age:27
Name:Suraj, Age:19

Sort by Age:
Name:Suraj, Age:19
Name:Neeraj, Age:22
Name:Pankaj, Age:25
Name:Pawan, Age:27

 

The above code is self explanatory, comment below if still you are facing and difficulty.

One comment

  • Mbunu

    Admin,

    Thanks for opening this blog and for the updating it with relevant topics and prompt responses. I have learnt a whole lot from your postings.
    I have bookmark this site. God bless

    Reply

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.