*
需求模拟
一个班级学生进行了多次模拟考试,求出每个学生模拟考试最优成绩。
学生实体类
class Student {
/**
* id
*/
private int id;
/**
* 姓名
*/
private String name;
/**
* 模拟考试次数
*/
private String subject;
/**
* 考试时间
*/
private Date examTime;
/**
* 成绩
*/
private int score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Date getExamTime() {
return examTime;
}
public void setExamTime(Date examTime) {
this.examTime = examTime;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Student(int id, String name, String subject, Date examTime, int score) {
this.id = id;
this.name = name;
this.subject = subject;
this.examTime = examTime;
this.score = score;
}
public Student() {
}
}
实现
@Test
void testStream() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//构造学生成绩List集合
List<Student> list = new ArrayList<>();
list.add(new Student(1, "张三", "第一次模拟考试", sdf.parse("2021-01-02 08:00:00"),99));
list.add(new Student(2, "张三", "第二次模拟考试", sdf.parse("2021-01-02 08:00:00"), 95));
list.add(new Student(3, "张三", "第三次模拟考试", sdf.parse("2021-01-02 08:00:00"), 105));
list.add(new Student(4, "李四", "第一次模拟考试", sdf.parse("2021-01-02 08:00:00"), 22));
list.add(new Student(5, "李四", "第二次模拟考试", sdf.parse("2021-01-02 08:00:00"), 85));
list.add(new Student(6, "李四", "第三次模拟考试", sdf.parse("2021-01-02 08:00:00"), 79));
list.add(new Student(7, "王五", "第一次模拟考试", sdf.parse("2021-01-02 08:00:00"), 25));
list.add(new Student(8, "王五", "第二次模拟考试", sdf.parse("2021-01-02 08:00:00"), 75));
list.add(new Student(9, "王五", "第三次模拟考试", sdf.parse("2021-01-02 08:00:00"), 95));
list.add(new Student(10, "赵六", "第一次模拟考试", sdf.parse("2021-01-02 08:00:00"), 55));
list.add(new Student(11, "赵六", "第二次模拟考试", sdf.parse("2021-01-02 08:00:00"), 99));
list.add(new Student(12, "赵六", "第三次模拟考试", sdf.parse("2021-01-02 08:00:00"), 95));
//集合处理按照学生姓名分组,求取每组学生三次模拟考试成绩最大值,处理结果为Map集合
Map<String,Student> collect = list.parallelStream().collect(
Collectors.groupingBy(Student::getName, Collectors.collectingAndThen(
Collectors.reducing((c1, c2) -> c1.getScore() > c2.getScore() ? c1 : c2),
Optional::get)
));
//map集合转List
List<Student> studentList=new ArrayList<>(collect.values());
//发现排序乱了,重新排序,中间comparator接口,如果为时间比较调用Long.compareTo()方法 Example:Collections.sort(undoTaskList, (o1, o2) -> Long.compare(o2.getExamTime().getTime(), o1.getExamTime().getTime()));
Collections.sort(studentList, (o1, o2) -> o2.getId() - o1.getId());
System.out.println(studentList.toString());
}