Saturday 31 October 2015

How to sort an ArrayList on Increasing and Decreasing Order

In this Java tutorial, I will teach you how to sort an ArrayList on both increasing and decreasing order of elements. Though, we will use ArrayList of Integers on examples, you can practically sort any list by using this technique. Only requirement is that your object should implement Comparable interface otherwise you need to pass Comparator implementation to sort objects stored inside list. The sort() method is defined inside java.util.Collections class. It is overloaded to accept a Comparator. The version which doesn't take any argument sort the given list on default order e.g. increasing order for integers. This is defined by their compareTo() method which comes from Comparable interface. The version which takes Comparator, uses that to sort the list, as we have done to sort the list in reverse or decreasing order.