Java Program to sort a list placing nulls in the end


Let us create a list first with string elements. Some of the elements are null in the List:

List<String> list = Arrays.asList("Jack", null, "Thor", null, "Loki", "Peter", null, "Hulk");

Now, sort the above list and place nulls in the end with nullsLast:

list.sort(Comparator.nullsLast(String::compareTo));

The following is an example to sort a list placing nulls in the end:

Example

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]

Updated on: 30-Jul-2019

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements