Java ArrayList sort()

The sort() method sorts the elements in an arraylist according to the specified order.

Example


Syntax of ArrayList sort()

The syntax of the sort() method is:

arraylist.sort(Comparator c)

Here, arraylist is an object of the ArrayList class.


sort() Parameters

The sort() method takes a single parameter.

  • comparator - specifies the sort order of the arraylist

sort() Return Values

The sort() method does not return any value. Rather it only changes the order of elements in an arraylist.


Example 1: Sort the ArrayList in Natural Order

Output

Unsorted ArrayList: [Python, Swift, C, JavaScript]
Sorted ArrayList: [C, JavaScript, Python, Swift]

In the above example, we have used the sort() method to sort the arraylist named languages. Notice the line,

languages.sort(Comparator.naturalOrder());

Here, the naturalOrder() method of the Java Comparator Interface specifies that elements are sorted in natural order (i.e. ascending order).

The Comparator interface also provides a method to sort elements in descending order. For example,

Example 2: Sort the ArrayList in Reverse Order

Output

Unsorted ArrayList: [Python, Swift, C, JavaScript]
Sorted ArrayList: [Swift, Python, JavaScript, C]

Here, the reverseOrder() method of the Comparator interface specifies that elements are sorted in reverse order (i.e. descending order).

Note: The Collections.sort() method is the more convenient method for sorting an arraylist.