W3docs

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.

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:


java— editable, runs on the server

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:


java— editable, runs on the server

This will also print the following output:


5
4
3
2
1

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