Comparator nullsLast() method in Java with examples
The nullsLast (java.util.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.
- When both elements are non-null, the specified Comparator determines the order.
- If 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> nullsLast (Comparator<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 greater than non-null and compares non-null objects with the supplied Comparator.
Below programs illustrate nullsLast(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.