像使用sql一样排序集合
作者:互联网
像使用sql一样排序集合
使用集合自己的排序功能,并写自己的Comparator接口
实践
@Test
public void Test6() {
Employee e1 = new Employee(1, 21, "zhangsan", "F");
Employee e2 = new Employee(2, 45, "lisi", "M");
Employee e3 = new Employee(3, 60, "wangwu", "M");
Employee e4 = new Employee(4, 32, "zhouliu", "F");
Employee e5 = new Employee(5, 28, "zhaoqi", "M");
Employee e6 = new Employee(6, 43, "qianba", "F");
List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5, e6);
// 都是正序
list.sort(Comparator.comparing(Employee::getGender).thenComparingInt(Employee::getAge));
list.forEach(System.out::println);
// 都是逆序
list.sort(Comparator.comparing(Employee::getGender).thenComparingInt(Employee::getAge).reversed());
list.forEach(System.out::println);
// 一逆一正
list.sort(Comparator.comparing(Employee::getGender).reversed().thenComparingInt(Employee::getAge));
list.forEach(System.out::println);
// 一正一逆
list.sort(Comparator.comparing(Employee::getGender).reversed().thenComparingInt(Employee::getAge).reversed());
list.forEach(System.out::println);
}
标签:Comparator,reversed,list,System,Employee,sql,集合,new,排序 来源: https://www.cnblogs.com/Oh-mydream/p/16387029.html