To sort a list in descending order in Java, you can use the sort
method along with a custom comparator.
In this example,
numbers
with integer values.sort
method on the numbers
list and pass the custom comparator to sort it in descending order.import java.util.Collections;
import java.util.List;
import java.util.Comparator;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println("Sorted list in descending order: " + numbers);
}
}
Sorted list in descending order: [8, 5, 3, 2, 1]
In this example,
words
with string values.sort
method on the words
list and pass the custom comparator to sort it in descending order.import java.util.Collections;
import java.util.List;
import java.util.Comparator;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("banana", "apple", "cherry");
Collections.sort(words, Comparator.comparing(String::length).reversed());
System.out.println("Sorted list in descending order: " + words);
}
}
Sorted list in descending order: [banana, cherry, apple]
In this tutorial, we learned How to Sort a List in Descending Order in Java language with well detailed examples.