I have decided to write a comprehensive guide on how to sort an ArrayList in Java. I have already written a guide on how to sort an array of object but how about an ArrayList. I have looked on several sites and seems like there is no guide yet or even its been there, the solution are quite simplistic.

On this guide we will be showing on different ways on how to sort a list from simple Strings down to Objects. Depending on the project requirements you can select any of these methods:

Sort an ArrayList using Collections.sort(List<T>)

On this example we have declared an ArrayList of professions in String format. And then we have just used the one of the handy method of Collections framework which is sort(List<T>). This is a very straight forward example however the sorting is done only in ascending order. If you have to sort in descending order we have to use the Collections.sort method but with the method argument Comparator. We will be tackling this on the next example.

Running the above code we will be having the following output

ArrayList Sort using Collections Framework Output

ArrayList Sort using Collections Framework Output

You would have noticed that we have a print out of each element of our ArrayList in ascending order. If we want to have the options to sort it in ascending order then we have to go through below example

Sort an ArrayList using Comparator

There were multiple variations of this example especially in dealing with Comparator. We would be showing these variations and you can select what suits you best.

This first example we will be showing on how to sort in descending order

Running the above example code we would be having a console output of elements of our array in descending order. Let’s take a look below for the result

Now that we have have explored the used of Comparator, lets go little bit further by creating our own Comparator. Lets take a look on below example

The above example is very robust and flexible solution. You would know later on that this solution will definitely solve all your sorting problem. First we have called the Collections.sort(List<T>, Comparator<T>). Inside this method it is asking for a Comparator which unlike previous example wherein we just used Collections.reverseOrder(). The reverseOrder() of the Collections framework returns a Comparator object that is descending in nature.

Since we want to have the flexibility of sorting, we have created our own anonymous Comparator and implemented its method which is the compare. Return values would be as follows

return value condition
0 if s1 and s2 is equal
-1 s1 < s2
1 s1 > s2

Running the above java example code will have the following result

As you would have noticed it is arranged in descending order. You might be thinking how to arrange then in descending order. the we just interchange the condition.


Now that we have covered most of the sorting algorithm, its now on your hand in selecting which best suits your needs.