How to use a Java8 lambda to sort a stream in reverse order?
Getting straight to the point, we sort a stream in reverse using sorted()
combined with Comparator
's reversed()
method.
For custom types or specific fields, we make use of Comparator.comparing()
:
To sort a list of files by lastModified
dates in reverse order, do this :
This ensures that the lower values are at the end of the list as reversed()
flips the natural order.
From lambdas to method references
Replacing lambda expressions with method references can improve the readability of the code and make it easier to maintain:
Here, MyClass::getValue
is a method reference used to extract the values to sort on, and the reversed()
method changes the sorting order.
Tweaking streams after sorting
After sorting streams, you might want to conduct more stream operations. Use Java 8 streams for efficient and readable code:
- Filtering
- Skipping and limiting
- Deleting elements directly from a stream compromises the immutability principle of streams. Instead, retrieve the results, and then modify the collected data.
Sorting scenarios you might encounter
Dealing with complex sorting cases is fairly common. Here are some examples:
- Nested attributes sorting:
- Multiple fields sorting:
- Handling nulls with care:
- Custom comparator for more complex logic:
Was this article helpful?