How to simplify a null-safe compareTo() implementation?

前端 未结 17 2087
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  温柔的废话
    2020-11-28 18:56

    I was looking for something similar and this seemed a bit complicated so I did this. I think it's a little easier to understand. You can use it as a Comparator or as a one liner. For this question you would change to compareToIgnoreCase(). As is, nulls float up. You can flip the 1, -1 if you want them to sink.

    StringUtil.NULL_SAFE_COMPARATOR.compare(getName(), o.getName());
    

    .

    public class StringUtil {
        public static final Comparator NULL_SAFE_COMPARATOR = new Comparator() {
    
            @Override
            public int compare(final String s1, final String s2) {
                if (s1 == s2) {
                    //Nulls or exact equality
                    return 0;
                } else if (s1 == null) {
                    //s1 null and s2 not null, so s1 less
                    return -1;
                } else if (s2 == null) {
                    //s2 null and s1 not null, so s1 greater
                    return 1;
                } else {
                    return s1.compareTo(s2);
                }
            }
        }; 
    
        public static void main(String args[]) {
            final ArrayList list = new ArrayList(Arrays.asList(new String[]{"qad", "bad", "sad", null, "had"}));
            Collections.sort(list, NULL_SAFE_COMPARATOR);
    
            System.out.println(list);
        }
    }
    

提交回复
热议问题