Null safe date comparator for sorting in Java 8 Stream

JavaJava 8Java Stream

Java Problem Overview


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();

Java Solutions


Solution 1 - Java

If it's the Items that may be null, use @rgettman's solution.

If it's the LocalDates 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.

Solution 2 - Java

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 are null, they are considered equal. If both are non-null, the specified Comparator is used to determine the order.

.sorted(Comparator.nullsLast(
     (e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt())))
.findFirst();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - JavaPaul BoddingtonView Answer on Stackoverflow
Solution 2 - JavargettmanView Answer on Stackoverflow