📜  java sort reverse lambda - Java (1)

📅  最后修改于: 2023-12-03 15:01:32.185000             🧑  作者: Mango

Java Sort Reverse with Lambda

In Java, you can sort collections using the Collections.sort() method. This method will sort the collection in ascending order by default, but what if you want to sort in descending order?

One way to do this is to use a lambda expression to define the sorting logic. Here is an example:

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);

Collections.sort(numbers, (a, b) -> b.compareTo(a));

System.out.println(numbers);

This will sort the list in descending order and output the following:

[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

In this example, the lambda expression (a, b) -> b.compareTo(a) is used to define the sorting logic. It compares the two elements a and b by calling the compareTo() method on b with a as the argument. This results in a negative number if b is greater than a, which indicates that b should come before a in the sorted list.

You can also use the Comparator.reverseOrder() method, which returns a comparator that sorts in reverse order. Here is an example:

Collections.sort(numbers, Comparator.reverseOrder());

System.out.println(numbers);

This produces the same output as the previous example.

Using lambda expressions and the Comparator.reverseOrder() method, you can easily sort collections in descending order in Java.