s-day07-使用Lambda表达式简化有参数有返回值的方法(比较器)

This commit is contained in:
2026-08-08 10:18:00 +08:00
parent 6b76e9333a
commit 7db048bd7d
2 changed files with 53 additions and 0 deletions
@@ -0,0 +1,31 @@
package com.inmind.lambda01;
import java.util.ArrayList;
import java.util.Collections;
/*
使用Lambda表达式简化有参数有返回值的方法(比较器)
使用比较器,对学生对象按成绩降序排序
*/
public class Demo02 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("小王1", 23, 100));
students.add(new Student("小王2", 25, 80));
students.add(new Student("小王3", 24, 90));
//使用比较器对学生集合排序
/*Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.score-o1.score;
}
});*/
//使用lambda表达式简化以上代码
Collections.sort(students,(Student o1, Student o2)->{
return o1.score-o2.score;
});
System.out.println(students);
}
}
@@ -0,0 +1,22 @@
package com.inmind.lambda01;
public class Student {
String name;
int age;
int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}