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

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 −


 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};



[Hadoop, JavaFX, OpenCV, null, null, null]
Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.