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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

list.sort(comparator)

Parameters

ParameterDescription
comparator
Comparator<? super E>
How to order elements; null for natural order.

Return value

Nothing (void).

Examples

Ascending and descending
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.

Sort objects by several keys
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

VersionChange
Java Java 8Added

Was this page helpful?