Java Arraylist Sort
# Java ArrayList sort() Method
[ Java ArrayList](#)
The `sort()` method sorts the elements in an ArrayList 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:**
* comparator - The ordering method
### Return Value
The `sort()` method does not return any value; it only changes the order of elements in the ArrayList.
### Example
Sorting in natural order, which is the alphabetical order:
## Example
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create an ArrayList
ArrayList sites =new ArrayList();
sites.add("");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website List: "+ sites);
System.out.println("Before Sorting: "+ sites);
// Sort elements in ascending order
sites.sort(Comparator.naturalOrder());
System.out.println("After Sorting: "+ sites);
}
}
The output of the above program is:
Website List: [, Google, Wiki, Taobao]Before Sorting: [, Google, Wiki, Taobao]After Sorting: [Google, , Taobao, Wiki]
In the example above, we used the `sort()` method to sort the ArrayList named `sites`.
Notice this line:
sites.sort(Comparator.naturalOrder());
Here, the `naturalOrder()` method of the Java `Comparator` interface specifies that the elements should be sorted in natural order (ascending).
The `Comparator` interface also provides a method to sort elements in descending order:
## Example
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// Create an ArrayList
ArrayList sites =new ArrayList();
sites.add("");
sites.add("Google");
sites.add("Wiki");
sites.add("Taobao");
System.out.println("Website List: "+ sites);
System.out.println("Before Sorting: "+ sites);
// Descending order
sites.sort(Comparator.reverseOrder());
System.out.println("Descending Order: "+ sites);
}
}
The output of the above program is:
Website List: [, Google, Wiki, Taobao]Before Sorting: [, Google, Wiki, Taobao]Descending Order: [Wiki, Taobao, , Google]
In the example above, the `reverseOrder()` method of the `Comparator` interface specifies that the elements should be sorted in reverse order (descending).
[ Java ArrayList](#)
YouTip