Java Collections sort() Method
Example
Sort a list of strings alphabetically:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars);
System.out.println(cars);
}
}
Definition and Usage
The sort() method sorts the items of a list in ascending order. Strings are sorted alphabetically, and numbers are sorted numerically.
You can also give a Comparator (an object that decides the order of two items) to sort the list in a different order.
Tip: Use Collections.reverseOrder() as the second argument to sort a list in descending order.
Syntax
One of the following:
public static void sort(List<T> list)
public static void sort(List<T> list, Comparator c)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The list to sort. |
| c | Optional. A Comparator that decides the order of the items. |
Technical Details
| Returns: | No return value. |
|---|
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods