The nullsFirst(java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values to be less than non-null. The null first operates by the following logic:
- The null element is considered to be less than non-null.
- When both elements are null, then they are considered equal.
- When both elements are non-null, the specified Comparator determines the order.
- If the specified comparator is null, then the returned comparator considers all non-null elements equal.
- The returned comparator is serializable if the specified comparator is serializable.
static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
Parameters: This method accepts a single parameter comparator which is a Comparator for comparing non-null values
Return value: This method returns a comparator that considers null to be less than non-null and compares non-null objects with the supplied Comparator.
Below programs illustrate nullsFirst(java.util.Comparator) method:
The output printed on console of IDE is shown below.
The output printed on console is shown below.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.