nullsLast
is a static method of the Comparator
interface that is used to return a Comparator
that considers null
elements to be greater than non-null elements.
The Comparator.nullsLast
method takes a Comparator
as a parameter, which is used to compare the non-null elements. If the passed comparator is null
, then the non-null values are considered to be equal.
Given two inputs and a non-null Comparator
as the parameter, the following scenarios are possible:
null
, the inputs are considered equal.Comparator
is used for comparison.null
and the other is non-null, then the null
input is considered to be greater than the non-null input.The Comparator
interface is defined in the java.util
package. To import the Comparator
interface, we use the following import statement:
import java.util.Comparator;
public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)
Comparator<? super T> comparator
: The Comparator
that is used to compare non-null values.This method returns a Comparator
.
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 nullsLast method to sort the arrayArrays.sort(strings, Comparator.nullsLast(Comparator.naturalOrder()));// print the sorted arraySystem.out.println("After sorting: " + Arrays.toString(strings));}}