javasortingarraylist

Sort a list, keeping elements in order but moving null elements to the end


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.

For example if the ArrayList is {1,2,null,6,5,null,3}, then I should get null values last: {1,2,6,5,3,null,null}.

The solution that I currently have is to construct a new ArrayList. If the value is null, I am not pushing it to new list otherwise I am adding it to the new ArrayList.

Is there a better solution?


Solution

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