Nice general way to sort nulls to the bottom, regardless?

后端 未结 5 560
北恋
北恋 2021-01-02 10:53

I\'m writing some custom Comparators, and I\'d like them to push null items to the bottom of the list, regardless of whether I\'m sorting ascending or descending. What\'s a

5条回答
  •  孤独总比滥情好
    2021-01-02 11:35

    I agree with Jon Skeet (it's so easy :). I tried to implement a very simple decorator:

    class NullComparators {
    
        static  Comparator atEnd(final Comparator comparator) {
            return new Comparator() {
    
                public int compare(T o1, T o2) {
                    if (o1 == null && o2 == null) {
                        return 0;
                    }
    
                    if (o1 == null) {
                        return 1;
                    }
    
                    if (o2 == null) {
                        return -1;
                    }
    
                    return comparator.compare(o1, o2);
                }
            };
        }
    
        static  Comparator atBeginning(final Comparator comparator) {
            return Collections.reverseOrder(atEnd(comparator));
        }
    }
    

    given a Comparator:

    Comparator wrapMe = new Comparator() {
          public int compare(String o1, String o2) {
              return o1.compareTo(o2);
          }
    };
    

    and some test data:

    List strings = Arrays.asList(null, "aaa", null, "bbb", "ccc", null);
    

    you can sort with nulls at end:

    Collections.sort(strings, NullComparators.atEnd(wrapMe));
    
    [aaa, bbb, ccc, null, null, null]
    

    or at beginning:

    Collections.sort(strings, NullComparators.atBeginning(wrapMe));
    
    [null, null, null, ccc, bbb, aaa]
    

提交回复
热议问题