How to sort an array of objects containing null elements in java?

Java 8Object Oriented ProgrammingProgramming

Whenever we try to sort elements with null values using the sort method it throws an exception.

The sort() method of the Arrays class also accepts a Comparator along with the array. Using comparator, you need to specify the order in which the elements need to be sorted.

Using this method push all the null elements to last and sort the elements −

Example

 Live Demo

import java.util.Arrays;
import java.util.Comparator;

public class ArrayWithNullsInOrder {
public static void main(String args[]) {
String[] myArray = {"JavaFX", null, "OpenCV", null, "Hadoop", null};

Arrays.sort(myArray,Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
System.out.println(Arrays.toString(myArray));
}
}

Output

[Hadoop, JavaFX, OpenCV, null, null, null]
raja
Published on 09-Jan-2018 07:22:17
Advertisements