Sorting a list with stream.sorted() in Java
Here's how you sort a list in a jiffy with Java's stream().sorted()
:
Want a custom sort, for example, sorting in descending order? Just inject a Comparator:
Just don't forget to import Collectors.toList()
and Comparator.reverseOrder()
.
In-depth explanation
Let's get our hands dirty and dive a bit deeper into the powerful Stream.sorted()
. It's a stateful intermediate operation, so it's like a deck of cards, you have to know all the cards before you can sort them.
In-place vs. new list
stream().sorted()
gives you a new sorted list, but if you want the original array modified, use list.sort()
:
This directly modifies the original list; discretion is advised! To keep your original list safe and untouched, remember to assign the sorted output to a new list.
Custom objects? No problem!
So your list is filled with custom objects and not just plain strings or integers? Simply tell Comparator.comparing()
how to compare your objects:
Hey look, it's all sorted by age now!
The power of chaining
You can chain comparators if you can't decide on a single property to sort by using thenComparing()
:
Look, we now have a fallback, it's like a polite tie-break in chess!
Pro tips and gotchas
Moving on to some imperative considerations and pro tips for putting stream().sorted()
into effective use.
High precision sorting
When sorting BigDecimal
and other high-precision numeric values, use suitable comparators:
The proof is in the pudding
Make sure your sort order is as expected. Unit tests can save your day, and reputation:
Simplified collection with JDK 16
Java 16 introduced toList()
. Going collector-less is the new fad:
Roll your own comparator
Lambda expressions in action for an explicit comparator:
Before-and-after comparison
A side-by-side comparison to confirm and marvel at your sorting skills:
Get a load off your chest
Can't contain your excitement over the sorted list? Let it out:
Got your imports right?
Don't forget the essential imports:
Was this article helpful?