Sort ArrayList in Java with code example

How to sort ArrayList in Java? This is a common need whenever you have to deal with a situation that needs to keep order of items.

There are two ways to sort ArrayList in Java. In the first approach, we will call Collections.sort() and the elements will be sorted by its natural order. Second approach is used for custom sorting and is done with the use of a Comparator class and comparable function.

Sort by natural order

The data types have a natural order. For example, number go like 0, 1, 2 …, the alphabets a,b,c.. etc. So, there is default sort implementation in Java that will sort the data elements by its natural order. Thus this approach works for data types that represent numbers and String.

Example to sort ArrayList that contain Integers

output:

The same approach will work for other Data types such as Double and String.

Here is the example with Double

output:

Sorting Array List in the descending order

You can sort in descending order in two different ways

  1. Call Collections.reverse() after a Collections.sort()
  2. While doing a Collections.sort(), pass a reverse Comparator. This Comparator you will get by calling Collections.reverseOrder().
Output
 

Click Here to Leave a Comment Below

Leave a Reply: