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 −

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]

Updated on: 16-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements