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

This commit is contained in:
2026-03-10 14:51:04 +08:00
parent e5508aff39
commit 9bfa87fd2b
2 changed files with 53 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
package com.inmind.lambda01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*
学习的内容使用Lambda表达式简化有参数有返回值的方法(比较器)
使用比较器,对学生对象按成绩降序排序
*/
public class Demo02 {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("张三1", 95));
students.add(new Student("张三2", 90));
students.add(new Student("张三3", 98));
/*Collections.sort(students, new Comparator<Student>() {
*//*
我-它:升序
它-我:降序
*//*
@Override
public int compare(Student o1, Student o2) {
return o2.score - o1.score;
}
});*/
Collections.sort(students,(Student o1, Student o2)->{ return o2.score - o1.score;});
System.out.println(students);
}
}

View File

@@ -0,0 +1,19 @@
package com.inmind.lambda01;
public class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
}