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;
}
}
}
private static void sort3(List<Bean> objects) {
objects.sort(Comparator.nullsLast(Comparator.comparing(Bean::getSort,
Comparator.nullsLast(Integer::compareTo))));
}
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));
}