一、问题说明
项目中碰到需要对List中的实体类Student(id,name,age)进行排序,年龄从小到大进行排序,为null的数据排到最后
现在把问题做个简化,List中只存放Integer(表示年龄),然后按以上规则进行排序
比如:
原有数组为[1, null, 5, null, null, 3, 6, null, 4]
经过排序后为[1, 3, 4, 5, 6, null, null, null, null]
二、问题解决
我们只要实现compare方法即可,该方法的参数是需要比较的两个数据(Integer o1,Integer o2)
如果两者都不为null,就直接进行数字比较;其中如果有一个为null,就将null排到后面
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(null);
list.add(5);
list.add(null);
list.add(null);
list.add(3);
list.add(6);
list.add(null);
list.add(4);
System.out.println("之前" + list);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// 写法1:
if (o1 != null && o2 != null) {
return o1.compareTo(o2);
} else {
return o1 == null ? 1 : -1;
}
// 写法2:
/*return o1 == null ?
1 :
(o2 == null ? -1 : o1.compareTo(o2));*/
}
});
System.out.println("之后" + list);
}
参考链接:http://www.itkeyword.com/doc/0528696999367324818/what-to-do-with-null-fields-in-compare