Null safe date comparator for sorting in Java 8 Stream

We Are Going To Discuss About Null safe date comparator for sorting in Java 8 Stream. So lets Start this Java Article.

Null safe date comparator for sorting in Java 8 Stream

  1. Null safe date comparator for sorting in Java 8 Stream

    You can turn your own null-unsafe Comparator into an null-safe one by wrapping it Comparator.nullsLast. (There is a Comparator.nullsFirst also.)

  2. Null safe date comparator for sorting in Java 8 Stream

    You can turn your own null-unsafe Comparator into an null-safe one by wrapping it Comparator.nullsLast. (There is a Comparator.nullsFirst also.)

Solution 1

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.

Advertisements

Original Author Paul Boddington Of This Content

Solution 2

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

Original Author rgettman Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment