Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collections.reverseOrder — a reverse-order comparator

Collections.reverseOrder creates a comparator reversing natural ordering or the ordering of a supplied comparator.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static <T> Comparator<T> reverseOrder()
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)

Collections.reverseOrder() returns a Comparator<T> reversing natural ordering. Elements must be mutually comparable through Comparable; for numbers, this means descending order.

Collections.reverseOrder(cmp) reverses the ordering defined by cmp. Passing null is equivalent to the no-argument call.

The call itself neither sorts nor modifies a collection. Pass its result to Collections.sort. Do not confuse it with Collections.reverse(list), which reverses the current element sequence without sorting. The example sorts a modifiable list in place.

Examples

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(2, 5, 1));
        Collections.sort(numbers, Collections.reverseOrder());
        System.out.println(numbers);
    }
}

Result

[5, 2, 1]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources