 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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
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
                    