I'm using this code to get the newest item. How can I get this to be null safe and sort with null dates last (oldest)?
Note: createDt is a joda LocalDate object.
Optional<Item> latestItem =
items.stream()
.sorted((e1, e2) -> e2.getCreateDt().compareTo(e1.getCreateDt()))
.findFirst();
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.