Java 25 (LTS) reference · List and ArrayList Methods
Java List sort() Method
Sort a list in place with a Comparator, or by natural order when you pass null. Collections.sort() does the same.
Java 25 (LTS) Since Java 8
Syntax
list.sort(comparator)
Parameters
| Parameter | Description |
|---|---|
comparatorComparator<? super E> |
How to order elements; null for natural order. |
Return value
Nothing (void).
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(5, 2, 9, 1));
nums.sort(null);
System.out.println(nums);
nums.sort(Comparator.reverseOrder());
System.out.println(nums);
}
}
Output
[1, 2, 5, 9] [9, 5, 2, 1]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
record Person(String name, int age) {}
List<Person> people = new ArrayList<>(List.of(new Person("Ana", 34), new Person("Ben", 28), new Person("Cleo", 34)));
people.sort(Comparator.comparingInt(Person::age).thenComparing(Person::name));
System.out.println(people);
}
}
Output
[Person[name=Ben, age=28], Person[name=Ana, age=34], Person[name=Cleo, age=34]]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
string.compareTo()· Compare two strings alphabetically: negative if this comes first, 0 if equal, positive if it comes after.stream.sorted()· Return a stream sorted by natural order or by a Comparator. The source collection is not changed.- Java Sorting and Comparators · tutorial