解释要做什么:
一个list列表,List<Student> list = new ArrayList<>();
里面有很多学生,属性name的内容为:bb,aa,cc.
让这个列表输出顺序变成,aa,bb,cc,看起来跟字典一样好查。
贴代码:
package com.example.practice;
import model.Student;
import java.text.Collator;
import java.util.*;
/**
* @author : null
* @date : 2018/11/20
* @description:
*/
public class StringNull {
public static void main(String[] args) {
Student student = new Student();
List<Student> list = new ArrayList<>();
student.setName("波比");
list.add(student);
Student student4 = new Student();
student4.setName("治安");
list.add(student4);
Student student3 = new Student();
student3.setName("啊啊");
list.add(student3);
Student student2 = new Student();
student2.setName("这个");
list.add(student2);
Student student99 = new Student();
student99.setName(null);
list.add(student99);
Student student1 = new Student();
student1.setName("啊波");
list.add(student1);
Student student88 = new Student();
student88.setName("a波");
list.add(student88);
Student student89 = new Student();
student89.setName("12");
list.add(student89);
Student student90 = new Student();
student90.setName(null);
list.add(student90);
for (Student student5 : list) {
System.out.println(student5.getName());
}
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//这里俩个是对属性判null处理,为null的都放到列表最下面
if (null==o1.getName()){
return 1;
}
if (null==o2.getName()){
return -1;
}
return Collator.getInstance(Locale.CHINESE).compare(o1.getName(),o2.getName());
}
});
System.out.println("输出排序后+++++++++++++++++++++++++++++++");
for (Student student5 : list) {
System.out.println(":::"+student5.getName());
}
}
}
输出结果:
波比
治安
啊啊
这个
null
啊波
a波
12
null
输出排序后+++++++++++++++++++++++++++++++
:::12
:::a波
:::啊啊
:::啊波
:::波比
:::这个
:::治安
:::null
:::null
简洁点:其中主要的就是这一段
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//这里俩个是对属性判null处理,为null的都放到列表最下面
if (null==o1.getName()){
return 1;
}
if (null==o2.getName()){
return -1;
}
return Collator.getInstance(Locale.CHINESE).compare(o1.getName(),o2.getName());
}
});
里面的compare(target,source)方法,
1.前面的值target大返回正值,
2.相等返回0,
3.小于后面的source返回负值。