Q:

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.

A:

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());   

A:

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());

