Lambda表达式的使用,集合元素排序,如果按工资降序排序,如果工资相同,按年龄升序排序,如果年龄相同,按姓名排序
代码
public static void main(String[] args) {
List<Student1> list = new ArrayList<>();
Student1 student1 = new Student1("张三", 23, 6060);
Student1 student2 = new Student1("李四", 24, 8000);
Student1 student3 = new Student1("王五", 23, 3000);
Student1 student4 = new Student1("赵六", 26, 3000);
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
Collections.sort(list,(stu1,stu2)->{
if (stu1.getSalary()==stu2.getSalary()){
return Integer.compare(stu1.getAge(),stu2.getAge());
} if (stu1.getAge()==stu2.getAge()){
return stu1.getName().compareTo(stu2.getName());
}else {
return -Integer.compare(stu1.getSalary(),stu2.getSalary());
}
});
list.stream().forEach(System.out::println);
}
遍历集合的结果
Student1(name=李四, age=24, salary=8000)
Student1(name=张三, age=23, salary=6060)
Student1(name=王五, age=23, salary=3000)
Student1(name=赵六, age=26, salary=3000)