1.自定义排序器
// Comparator.comparing(list, Comparator);
// list 传入要排序的参数列表,Comparator 来指定一个排序器,这里可以用匿名内部类来实现一个自定义排序规则。
public static void main(String[] args) {
Collator instance = Collator.getInstance(Locale.CHINA);
instance.setStrength(Collator.PRIMARY);
List<Employee> tempList = list.stream().sorted(Comparator.comparing(Employee::getName, instance)).collect(Collectors.toList());
for (int i = 0; i < tempList.size(); i++) {
System.out.println(tempList.get(i));
}
}
private void test1() {
List<Employee> collect = list.stream().sorted(Comparator.comparing(Employee::getGrade, (s1,s2)->{
if ("5".equals(s1)) {
return -1;
} else {
return 0;
}
})
// 这个排序和下面的排序效果完全不一样。
// .thenComparing(Employee::getName, Comparator.reverseOrder())
// .thenComparing(Employee::getName).reversed()
)
.collect(Collectors.toList());
for (Employee employee : collect) {
System.out.println(employee);
}
}
static final List<Employee> list = Arrays.asList(
new Employee("张三", "14", "6"),
new Employee("李四", "16", "3"),
new Employee("王子", "16", "3"),
new Employee("王五", "12", "5")
);
static class Employee {
// get set方法省略了
String name;
String age;
String grade;
public Employee(String name, String age, String grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
}
2.中文首字母排序
Collator instance = Collator.getInstance(Locale.CHINA);
instance.setStrength(Collator.PRIMARY);
List<Employee> tempList = list.stream().sorted(Comparator.comparing(Employee::getName, instance)).collect(Collectors.toList());