I'm using this to get the newest item. How can I get this to be null safe and sort with null dates last (oldest). createDt is a joda LocalDate object.
Optional<Item> latestItem = items.stream() .sorted((e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt())) .findFirst();
Comparator nullsLast() method in Java with examples When both elements are null, then they are considered equal. When both elements are non-null, the specified Comparator determines the order. If specified comparator is null, then the returned comparator considers all non-null elements equal.
We are sorting using the nullsFirst() method, after sorting, null values will come in the start and then the sorting list of employees will come sorted by date of birth. To sort on natural order, after ordering null values, use Comparator. nullsFirst( Comparator. naturalOrder() ).
We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
If it's the Item
s that may be null, use @rgettman's solution.
If it's the LocalDate
s that may be null, use this:
items.stream() .sorted(Comparator.comparing(Item::getCreateDt, Comparator.nullsLast(Comparator.reverseOrder())));
In either case, note that sorted().findFirst()
is likely to be inefficient as most standard implementations sort the entire stream first. You should use Stream.min instead.
You can turn your own null-unsafe Comparator
into an null-safe one by wrapping it Comparator.nullsLast
. (There is a Comparator.nullsFirst
also.)
Returns a null-friendly comparator that considers
null
to be greater than non-null. When both arenull
, they are considered equal. If both are non-null, the specifiedComparator
is used to determine the order.
.sorted(Comparator.nullsLast( (e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt()))) .findFirst();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With