Java ArrayListsort() Method
Example
Sort a list in alphabetical order:
import java.util.ArrayList;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"); cars.sort(null); System.out.println(cars); }}Definition and Usage
Thesort() method sorts items in the list. AComparator can be used to compare pairs of elements. The comparator can be defined by a lambda expression which is compatible with thecompare() method of Java'sComparator interface.
Ifnull is passed into the method then items will be sorted naturally based on their data type (e.g. alphabetically for strings, numerically for numbers). Non-primitive types must implement Java'sComparable interface in order to be sorted without a comparator.
Syntax
public void sort(Comparatorcompare)Parameter Values
| Parameter | Description |
|---|---|
| compare | Required. A comparator or lambda expression which compares pairs of items in the list. Passnull to compare items naturally by their data type. |
Technical Details
| Java version: | 1.8+ |
|---|
More Examples
Example
Use a lambda expression to sort a list in reverse alphabetical order:
import java.util.ArrayList;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"); cars.sort( (a, b) -> { return -1 * a.compareTo(b); } ); System.out.println(cars); }}Related Pages
❮ ArrayList Methods

