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

后端 未结 5 516
北恋
北恋 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:27

    Following up on dfa's answer - what I want is that the nulls sort at the end without affecting the order of the non-nulls. So I want something more along the lines of this:

    public class NullComparatorsTest extends TestCase {
        Comparator  forward = new Comparator() {
                                        public int compare(String a, String b) {
                                            return a.compareTo(b);
                                        }
                                    };
    
        public void testIt() throws Exception {
            List strings = Arrays.asList(null, "aaa", null, "bbb", "ccc", null);
            Collections.sort(strings, NullComparators.atEnd(forward));
            assertEquals("[aaa, bbb, ccc, null, null, null]", strings.toString());
            Collections.sort(strings, NullComparators.atBeginning(forward));
            assertEquals("[null, null, null, aaa, bbb, ccc]", strings.toString());
        }
    }
    
    public class NullComparators {
        public static  Comparator atEnd(final Comparator comparator) {
            return new Comparator() {
                public int compare(T a, T b) {
                    if (a == null && b == null)
                        return 0;
                    if (a == null)
                        return 1;
                    if (b == null)
                        return -1;
                    return comparator.compare(a, b);
                }
            };
        }
    
        public static  Comparator atBeginning(final Comparator comparator) {
            return new Comparator() {
                public int compare(T a, T b) {
                    if (a == null && b == null)
                        return 0;
                    if (a == null)
                        return -1;
                    if (b == null)
                        return 1;
                    return comparator.compare(a, b);
                }
            };
        }
    }
    

    Full credit to dfa, though - this is just a minor modification of his work.

提交回复
热议问题