# 排序比较器 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.get(0).putSort(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


03-05 3952

02-22 1万+

07-22 817

09-10 1430

05-28 605

09-07 389

04-11 8847

08-22 3423

03-10 1万+

09-21 673

10-14 57

11-01 746

08-12 3058

03-26 3504

04-06 55

06-03 355

11-12 970

#### 自定义比较器Comparator排序集合里面的元素,并且写出xml

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客