Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array with null values [duplicate]

Tags:

java

arrays

I have a program that allows user to delete an element from an array and I am trying to sort them in alphabetic order using compareTo(); through a for loop. However, the null values are giving me problems. For example an array with null values:

String[] myArray = {"Apple", "Banana", null, "Durian", null, null, "Grapes"};

When Java is comparing them and reads a null value, it would give me a NullPointerException.

Is there any way that I can sort this array with null values at the back? For example:

{"Apple", "Banana", "Durian", "Grapes", null, null, null}

I know that using Vectors can solve the problem but I am just curious if there is any way that I can just do it without changing my array to vectors.

like image 733
jl90 Avatar asked Jan 25 '13 02:01

jl90


People also ask

How will you sort an array with many duplicated values?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

How do I sort null values?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

Can arrays have NULL values?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.


2 Answers

try this

    Arrays.sort(myArray, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1 == null && o2 == null) {
                return 0;
            }
            if (o1 == null) {
                return 1;
            }
            if (o2 == null) {
                return -1;
            }
            return o1.compareTo(o2);
        }});

it produces the required order

like image 146
Evgeniy Dorofeev Avatar answered Oct 09 '22 15:10

Evgeniy Dorofeev


write your own Comparator that accepts null values, and pass that comparator to the Arrays.sort() method

like image 35
AlexWien Avatar answered Oct 09 '22 16:10

AlexWien