Java sort()

The sort() method of the collections framework uses the merge sort algorithm to sort elements of a collection.

The merge sort algorithm is based on divide and conquers rule. To learn more about the merge sort, visit Merge Sort Algorithm.

Let's take an example of the sort() method.


Example: Sorting in Ascending Order

Output

Unsorted ArrayList: [4, 2, 3]
Sorted ArrayList: [2, 3, 4]

As you can see, by default, the sorting occurs in natural order (ascending order). However, we can customize the sorting order of the sort() method.


Customized Sorting Order

In Java, the sort() method can be customized to perform sorting in reverse order using the Comparator interface.


Example: Sorting in Descending Order

Output

Unsorted ArrayList: [4, 2, 3]
Natural Sorting: [2, 3, 4]
Customized Sorting: [4, 3, 2]

In the above example, we have used the sort() method with CustomComparator as an argument.

Here, CustomComparator is a class that implements the Comparator interface. Learn more about the Java Comparator Interface.

We then override the compare() method. The method will now sort elements in reverse order.