Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda comparator with null value check [duplicate]

Tags:

lambda

java-8

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?

like image 215
Gabber Avatar asked Oct 06 '16 08:10

Gabber


People also ask

How do you handle null in Comparator?

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.

How do you sort a list with null values in Java 8?

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.

How do you sort a list with null values?

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

How do you use lambda Comparator?

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.


1 Answers

There are default implementations within Comparator you can use: nullsFirst or nullsLast:

Comparator.comparing(YourObject::getStartDate, 
  Comparator.nullsFirst(Comparator.naturalOrder())
)
like image 57
flo Avatar answered Oct 13 '22 22:10

flo