Java ArrayList sort()

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

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

import java.util.ArrayList;
import java.util.Comparator;

class Main {
  public static void main(String[] args) {

    // create an ArrayList
    ArrayList<String> languages = new ArrayList<>();

    // add elements to ArrayList
    languages.add("Python");
    languages.add("Swift");
    languages.add("C");
    languages.add("JavaScript");
    System.out.println("Unsorted ArrayList: " + languages);

    // sort the ArrayList in ascending order
    languages.sort(Comparator.naturalOrder());
    System.out.println("Sorted ArrayList: " + languages);
  }
}

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 method to sort elements in descending order. For example,

Example 2: Sort the ArrayList in Reverse Order

import java.util.ArrayList;
import java.util.Comparator;

class Main {
  public static void main(String[] args) {

    // create an ArrayList
    ArrayList<String> languages = new ArrayList<>();

    // add elements to ArrayList
    languages.add("Python");
    languages.add("Swift");
    languages.add("C");
    languages.add("JavaScript");
    System.out.println("Unsorted ArrayList: " + languages);

    // sort the ArrayList in ascending order
    languages.sort(Comparator.reverseOrder());
    System.out.println("Sorted ArrayList: " + languages);
  }
}

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.