Comparator null handling Examples using nullsFirst() and nullsLast() Methods Java 8

What about null values while we sorting an Object on the basis of some property. Suppose I want to sort list of values and I know that in that list I have some null values. Should I put them at the beginning of the sorted list or at the end of sorted list. We have comparator for that.

The first comparator is called nullFirst(), it is static method from Comparator Interface and it will put null values at the beginning of that list.

In same way if I want to put null values at the end of the list, we get nullLast() static method of Comparator Interface.

Comparator nullsFirst() and nullsLast() Methods Example Java 8

Let’s assume that the last name property of Employee can be null. We will write a Comparator that would sort a collection of Employee in the ascending order of a Employee’s last name. Then we can think that what should be sorting criteria for the null values of last name property? Let’s see by example keeping the Employee objects, having null last names, towards the front and then in the end of the sorted Employee collection.

Output of the above programme:

In the above example using nullsFirst(), the comparator places the two Employee objects with the sort key last name having null values before the other Employee objects in the list.
Sameway, using nullsLast(), the comparator places these two Employee objects having sort key last name nll values after the other Employee objects in the list.


Leave a Reply