What is the Comparator.nullsLast method in Java?

Overview

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:

  • When both the inputs are null, the inputs are considered equal.
  • When both the inputs are non-null, the supplied Comparator is used for comparison.
  • When one of the inputs is 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;

Syntax

public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)

Parameters

  • Comparator<? super T> comparator: The Comparator that is used to compare non-null values.

Return value

This method returns a Comparator.

Code

import java.util.Arrays;
import java.util.Comparator;
public class Main{
public static void main(String[] args) {
// Collection of strings
String[] strings = {null, "hello", "educative", null, "edpresso"};
// print the string collection
System.out.println("Before sorting: " + Arrays.toString(strings));
// Using the nullsLast method to sort the array
Arrays.sort(strings, Comparator.nullsLast(Comparator.naturalOrder()));
// print the sorted array
System.out.println("After sorting: " + Arrays.toString(strings));
}
}

Free Resources