Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparator.naturalOrder(): natural ordering in Java

Use `Comparator.naturalOrder()` to sort by the type’s own order: case-sensitive lexicographic order for `String` and numeric order for `Integer`.

Version: Java SE 21

Syntax

static <T extends Comparable<? super T>> Comparator<T> naturalOrder()

Comparator.naturalOrder() is a static method on java.util.Comparator, available since Java 8. It returns a serializable comparator that uses the elements’ compareTo method; the call itself does not sort anything. The bound T extends Comparable<? super T> means T must implement Comparable for itself or one of its supertypes.

For String, the order is lexicographic: the first differing UTF-16 code unit decides, and if one string is a prefix of the other, the shorter one comes first. This comparison is case-sensitive and does not depend on the locale. That is why "Banana" comes before "apple", and "10" before "2".

For Integer, the signed numeric value determines the order: -3 comes before 2, and 2 before 10. The comparator does not turn text into numbers. List.sort uses the supplied comparator to reorder the same list; both ArrayList instances in the example are modifiable.

Comparing with null throws NullPointerException. To put null values last, use Comparator.nullsLast(Comparator.naturalOrder()). To reverse the natural order, use Comparator.reverseOrder().

Examples

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        var words = new ArrayList<>(List.of("apple", "Banana", "2", "10"));
        var numbers = new ArrayList<>(List.of(2, 10, -3));

        words.sort(Comparator.naturalOrder());
        numbers.sort(Comparator.naturalOrder());

        System.out.println(words);
        System.out.println(numbers);
    }
}

Result

[10, 2, Banana, apple]
[-3, 2, 10]

The first line shows that the text `"10"` comes before `"2"`, and `"Banana"` before `"apple"`. On the second line, the number `2` comes before `10`.

Related lessons

  • Java · Lesson 35 · Intermediate · Version: 2

Sources