I've implemented a sorting on a collection using a lambda expression for the comparison. I have to check for null values, so I came up with this solution for the comparator
(a,b)->(
(a.getStartDate() == null)
? ( (b.getStartDate() == null) ? 0 : -1)
: ( (b.getStartDate() == null)?1:a.getStartDate().compareTo(b.getStartDate()) )
);
I've already checked some questions, like this, but they all refer to pre-lambda code.
Do java lambda expressions give me the chance to avoid the two 'if' statements? Can I perform the task in a cleaner way?
Comparator) method returns comparator that is a null-friendly comparator and considers null values greater than non-null. The null first operates by the following logic: The null element is considered to be greater than non-null. When both elements are null, then they are considered equal.
Java 8 – Sorting List of Integers with null values : Here, we are sorting list of integers which contains null values using static methods nullsFirst() & nullsLast() of Comparator interface. Comparator. nullsFirst() – this comparator helps to push null values to first/starting position.
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() ).
In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List. 1. Classic Comparator example. Comparator<Developer> byName = new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.
There are default implementations within Comparator you can use: nullsFirst
or nullsLast
:
Comparator.comparing(YourObject::getStartDate,
Comparator.nullsFirst(Comparator.naturalOrder())
)
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