How to Sort ArrayList in Java

ArrayList in Java is an ordered collection in the sense that it maintains the insertion order of the elements but sometimes you may have a requirement to sort an ArrayList in ascending order or descending order. In this post we’ll see How to sort an ArrayList in Java.

Methods used to sort ArrayList in Java

Collection class in Java provides many utility methods that operate on collection, this class also has sort method. Actually sort() method is overloaded in Collections class and there are 2 variants.

void sort(List list)– Sorts the specified list into ascending order, according to the natural ordering of its elements.

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

Sorting ArrayList example

If you want to sort ArrayList in ascending order then you can just pass the List in Collections.sort() method. All the wrapper classes in Java (Integer, Long etc.), String, Date implements Comparable interface and provide implementation of compareTo() method which decides their natural ordering. So, if you have an ArrayList of String, Integer, Long, Float, Date is will be sorted in ascending order by using sort() method.

Sorting ArrayList of String example code

Output

Sorting ArrayList in descending order

If you want to sort ArrayList in reverse order of the natural ordering then Collections class has a reverseOrder() method that can be used. Alternatively you can write your own Comparator.

reverseOrder()– Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Sorting Arraylist using reverseOrder method

Since reverseOrder() method returns a Comparator so you will have to use Collections.sort() method where you can pass Comparator as an argument.

Output

Sorting Arraylist by providing own custom Comparator

Collections.reverseOrder() method returns an implementation of Comparator class. Same way you can write your own Comparator for the ordering you want to impose and use that to sort the List.

Output

That’s all for the topic How to Sort ArrayList 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.