s-day07--使用Lambda表达式简化有参数有返回值的方法(比较器)
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
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<>();
|
||||
Collections.addAll(students,
|
||||
new Student("刘备",88),
|
||||
new Student("关羽",98),
|
||||
new Student("张飞",78)
|
||||
);
|
||||
System.out.println("排序之前:"+students);
|
||||
//sort方法排序
|
||||
Collections.sort(students, new Comparator<Student>() {
|
||||
@Override
|
||||
public int compare(Student o1, Student o2) {
|
||||
return o2.score-o1.score;
|
||||
}
|
||||
});
|
||||
|
||||
System.out.println("排序之后:"+students);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.inmind.lambda01;
|
||||
|
||||
public class Student{
|
||||
String name;
|
||||
Integer score;
|
||||
|
||||
public Student(String name, Integer score) {
|
||||
this.name = name;
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Student{" +
|
||||
"name='" + name + '\'' +
|
||||
", score=" + score +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user