Java Program to sort a list placing nulls in the end

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 02-May-2019 10:13:30
Advertisements