Administrator
发布于 2021-07-29 / 2612 阅读 / 0 评论 / 0 点赞

java中排序比较器 Comparator 考虑为null的情况

java中排序比较器 Comparator 考虑为null的情况

public class Comptor {
    public static void main(String[] args) {
        List<Bean> objects = new ArrayList<>();
        Random random = new Random(1);
        for (int i = 0; i < 10; i++) {
            objects.add(new Bean(random.nextInt()));
        }
        objects.get(0).putSort(null);
        objects.add(null);
        objects.forEach(System.out::println);

    }

    static class Bean{
        private Integer sort;

        public Bean(int sort) {
            this.sort = sort;
        }

        public Integer getSort() {
            return sort;
        }

        @Override
        public String toString() {
            return "Bean{" +
                    "sort=" + sort +
                    '}';
        }

        public Bean putSort(Integer sort) {
            this.sort = sort;
            return this;
        }
    }

}
	/**Bean可能为null的兼容*/
    private static void sort3(List<Bean> objects) {
        objects.sort(Comparator.nullsLast(Comparator.comparing(Bean::getSort, 
        	Comparator.nullsLast(Integer::compareTo))));
    }
	/**比较字段可能为null时的兼容*/
    private static void sort2(List<Bean> objects) {
        objects.sort(Comparator.comparing(Bean::getSort,
        	 Comparator.nullsLast(Integer::compareTo)));
    }

    /** 正常排序*/
    public static  void sort1(List<Bean> objects) {
        objects.sort(Comparator.comparingInt(Bean::getSort));
    }

评论