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

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

    In Java 8, you can use the Comparator.nullsLast and Comparator.nullsFirst static methods to have more null-friendly comparators. Suppose you have a Fruit class like the following:

    public class Fruit {
        private final String name;
        private final Integer size;
    
        // Constructor and Getters
    }
    

    If you want to sort a bunch of fruits by their size and put the nulls at the end:

    List fruits = asList(null, new Fruit("Orange", 25), new Fruit("Kiwi", 5));
    

    You can simply write:

    Collections.sort(fruits, Comparator.nullsLast(Comparator.comparingInt(Fruit::getSize)));
    

    And the result would be:

    [Fruit{name='Kiwi', size=5}, Fruit{name='Orange', size=25}, null]
    

提交回复
热议问题