
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort 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
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]
Advertisements