What is the Comparator.nullsFirst() method in Java?
The nullsFirst() method is used to return a Comparator, which considers the null elements to be lesser than the non-null elements.
It takes a Comparator as a parameter, which is then used for the comparison of the non-null elements.
Given two inputs and a non-null comparator as the parameter, the following scenarios are possible:
| First input | Second input | Behaviour |
|---|---|---|
| null | null | The inputs are considered equal. |
| non-null | non-null | The supplied comparator is used for comparison. |
| null | non-null | First input is considered to be less than the second input. |
| non-null | null | Second input is considered to be less than the first input. |
The Comparator interface is defined in the java.util package. To import the Comparator interface, we check the following import statement:
import java.util.Comparator;
Syntax
public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
Parameters
Comparator<? super T> comparator: This is the Comparator that is used for comparing the non-null values.
Return value
This method returns a Comparator which considers the null elements to be lesser than the non-null elements.
import java.util.Arrays;import java.util.Comparator;public class Main{public static void main(String[] args) {// Collection of stringsString[] strings = {null, "hello", "educative", null, "edpresso"};// print the string collectionSystem.out.println("Before sorting: " + Arrays.toString(strings));// Using the nullsFirst method to sort the arrayArrays.sort(strings, Comparator.nullsFirst(Comparator.naturalOrder()));// print the sorted arraySystem.out.println("After sorting: " + Arrays.toString(strings));}}
Code explanation
- Lines 1-2: We import the relevant packages.
- Line 8: We define a collection of strings containing
nulland non-null values. - Line 11: We print the string collection that we defined in line 8.
- Line 14: We sort the collection by using the
Arrays.sort()method and passing theComparator.nullsFirst()method as a parameter. - Line 17: We print the sorted collection.