Easy Tutorial
❮ Java Polymorphism Java Arraylist Add ❯

Java ArrayList sort() Method

Java ArrayList

The sort() method sorts the elements of the dynamic array according to the specified order.

The syntax for the sort() method is:

arraylist.sort(Comparator c)

Note: arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

The sort() method does not return any value; it only changes the order of the elements in the dynamic array list.

Example

Sorting in natural order, here is the alphabetical order:

Example

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

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

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("tutorialpro");
        sites.add("Google");
        sites.add("Wiki");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

        System.out.println("Unsorted: " + sites);

        // Sort elements in ascending order
        sites.sort(Comparator.naturalOrder());
        System.out.println("Sorted: " + sites);
    }
}

Executing the above program outputs:

Website List: [tutorialpro, Google, Wiki, Taobao]
Unsorted: [tutorialpro, Google, Wiki, Taobao]
Sorted: [Google, tutorialpro, Taobao, Wiki]

In the above example, we used the sort() method to sort the dynamic array named sites.

Note this line:

sites.sort(Comparator.naturalOrder());

Here, the naturalOrder() method of the Java Comparator interface specifies that elements should be sorted in natural order (ascending).

The Comparator interface also provides a method for sorting elements in descending order:

Example

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

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

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("tutorialpro");
        sites.add("Google");
        sites.add("Wiki");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

        System.out.println("Unsorted: " + sites);

        // Descending order
        sites.sort(Comparator.reverseOrder());
        System.out.println("Sorted in Descending Order: " + sites);
    }
}

Executing the above program outputs:

Website List: [tutorialpro, Google, Wiki, Taobao]
Unsorted: [tutorialpro, Google, Wiki, Taobao]
Sorted in Descending Order: [Wiki, Taobao, tutorialpro, Google]

In the above example, the reverseOrder() method of the Comparator interface specifies that elements should be sorted in reverse order (descending).

Java ArrayList

❮ Java Polymorphism Java Arraylist Add ❯