排序比较器 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);

    }
	/**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));
    }

    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{sort=-1465154083}
Bean{sort=-1242363800}
Bean{sort=-138487339}
Bean{sort=155629808}
Bean{sort=431529176}
Bean{sort=892128508}
Bean{sort=1429008869}
Bean{sort=1749940626}
Bean{sort=1761283695}
Bean{sort=null}
null
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读