How to Sort ArrayList of Objects in Java

In this post we’ll see how to sort ArrayList of objects in Java. In the post How to Sort ArrayList in Java we have already seen how you can sort ArrayList of String, Date or any Wrapper class (Integer, Float etc.). All those classes already implement Comparable interface so you just need to pass the list to Collections.sort() method to sort it.

When you need to sort ArrayList of custom objects in Java, you will have to make sure that the class whose objects are stored in the ArrayList implements Comparable interface or you have a Comparator implementation ready to be used.

Implementation of the Comparable interface will set the natural ordering of the class. If your class doesn’t implement Comparable interface and Comparator is also not specified then using an ArrayList of such objects with sort() method will result in compile time error.

If you want to sort in any other order rather than natural ordering set by Comparable then you can implement Comparator and use the sort() method of the Collections class which takes Comparator as argument.

sort(List<T> list, Comparator<? super T> c)– Sorts the specified list according to the order induced by the specified comparator.

Sorting ArrayList of objects using Comparable

Here we have a class Employee and you want to sort by empName field of the class. Then Employee class should implement the Comparable interface and provide implementation of the compareTo() method.

Then you can pass ArrayList of Employee class object in Collections.sort() method.

Output

Sorting ArrayList of objects using Comparator

Employee class used above implements Comparable and provide implementation of the compareTo() method to sort by name. This sort order becomes the natural ordering of the class but now you are bound with that ordering. What if you want to sort by age now? Answer is write a separate method or class implementing Comparator interface. By implementing Comparator you can have more than one option for sorting.

Here is the updated Employee class with 2 Comparator implementations added to sort by age or to sort by name in reverse order.

Then you can pass these Comparator implementations with the sort() method to get the required ordering.

Output

That’s all for the topic How to Sort ArrayList of Objects in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

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.