Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String sorting null values

I have a string arraylist with some null values and some strings. I don't want to sort the arraylist but I should sort the arraylist such that null values comes last. Lets say arraylist is {1,2,null,6,5,null, 3}, I should get null values last {1,2,6,5,3,null,null}.

Solution , I currently have: Right now, I am constructing new arraylist and If the value is null, I am not pushing it to new list otherwise I am adding it to new arraylist.

Any other better solution?

Thanks for the help.

like image 694
Stunner Avatar asked Dec 01 '15 09:12

Stunner


4 Answers

If you are using Java 8, you can easily build the comparator you need:

Arrays.sort(stringArray, Comparator.nullsLast(Comparator.naturalOrder()));

But if you not using java 8 you can have a comparator like below

public class StringNullComparator implements Comparator<String> {
    public int compare(String stringOne, String stringTwo) {
        if (stringOne != null && stringTwo != null)
            return stringOne.compareTo(stringTwo);
        return (stringOne == stringTwo)?0:(stringOne==null? 1 : -1);
    }
}

And you can use at stated below

Arrays.sort(stringArray, new StringNullComparator());   
like image 169
Viraj Nalawade Avatar answered Oct 11 '22 20:10

Viraj Nalawade


Custom Comparator to pass to sort:

public class StringComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        if (s1 != null && s2 != null)
            return s1.compareTo(s2);
        return (s1 == null) ? 1 : -1;
    }
}

then:

Collectios.sort(list, new StringComparator());
like image 42
user2390182 Avatar answered Oct 11 '22 20:10

user2390182


If you want to avoid explicitly iterating over the whole list you could use ArrayList.indexOf() to find the null values, then remove() them. If you want to keep the values in the list you can then just add a null value to the end of the list. However I would imagine this approach is not great in terms of performance if this is a concern.

like image 40
ewanc Avatar answered Oct 11 '22 20:10

ewanc


You can use NullComparator from apache.

Collections.sort(list, new NullComparator());
like image 30
2787184 Avatar answered Oct 11 '22 20:10

2787184