Sort a List Placing Nulls at the End in Java



In this article, we will learn how to sort lists containing null values in Java and ensure these nulls are kept at the bottom while upper elements remain in order. This can be done using Comparator.nullsLast, which sorts the non-null elements and places all null elements at last.

Problem Statement

A list of strings with some string values and nulls is given. Write a Java program to sort a list placing nulls in the end.

Input

Initial List = ("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk")

Output

Initial List = [Jack, null, Thor, null, Loki, Peter, null, Hulk] List placing nulls at the end = [Hulk, Jack, Loki, Peter, Thor, null, null, null]

Steps to sort a list placing nulls in the end

Following are the steps to sort a list placing nulls in the end:

  • Firstly, we will import the Arrays class, Comparator, and List from java.util package.
  • Now, create a list containing values with some null and non-null elements.
  • Select the sorting method (eg. Comparator.nullsLast) that allows null-values.
  • Apply the sorting technique to ensure non-null elements are in order and all nulls are positioned at the end.

Java program to sort a list placing nulls in the end

The following is an example of sorting a list and placing nulls in the end:

Open Compiler
import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String... args) { List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk"); System.out.println("Initial List = "+list); list.sort(Comparator.nullsLast(String::compareTo)); System.out.println("List placing nulls in the end = "+list); } }

Output

Initial List = [Jack, null, Thor, null, Loki, Peter, null, Hulk]
List placing nulls in the end = [Hulk, Jack, Loki, Peter, Thor, null, null, null]

Code explanation

The above code creates a list of strings with some null values and sorts it alphabetically, placing all null values at the end. This sorting is performed using Comparator.nullsLast(String::compareTo) to sort the non-null elements while moving the null entries to the end. The initial unsorted list is printed, followed by the sorted list where null values appear at the end.

Updated on: 2024-10-30T18:44:59+05:30

645 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements