How to use a Java8 lambda to sort a stream in reverse order?

To use a Java 8 lambda to sort a stream in reverse order, you can use the sorted() method of the Stream interface and pass a lambda function that compares the elements in reverse order.

Here's an example of how you can use a lambda to sort a stream of integers in reverse order:

import java.util.*;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(4, 5, 3, 1 , 2);

    numbers.stream()
           .sorted((a, b) -> b - a)
           .forEach(System.out::println);
  }
}

This will print the following output:

5
4
3
2
1

You can also use the reverseOrder() method of the Comparator class to get a comparator that compares elements in reverse order and pass it to the sorted() method:

import java.util.*;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(4, 5, 3, 1, 2);

   numbers.stream()
       .sorted(Comparator.reverseOrder())
       .forEach(System.out::println);
 }
}

This will also print the following output:

5
4
3
2
1

I hope this helps! Let me know if you have any questions.