JAVA lambada表达式查询分组中的最大值

查询出每个班级年龄最大的学生和年龄最小的学生

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
public class MaxByMinBy {
public static void main(String[] args) {
Student student = new Student("Bruce", 27, "A");
Student student1 = new Student("Michael", 23, "A");
Student student2 = new Student("Lee", 22, "B");
Student student3 = new Student("Lucy", 25, "B");
List<Student> students = Arrays.asList(student, student1, student2, student3);
Comparator<Student> ageComparator = Comparator.comparing(Student::getAge);
// 查询年纪最小 使用 minBy
Map<String, Optional<Student>> collect = students.stream().collect(Collectors.groupingBy(Student::getClassName, Collectors.reducing(BinaryOperator.maxBy(ageComparator))));
collect.forEach((k, v) -> System.out.println("Class:" + k + " Age:" + v.get().getAge() + " Name:" + v.get().getName()));
}

@Data
@AllArgsConstructor
static class Student {
private String name;
private Integer age;
private String className;

}
}

运行结果

1
2
Class:A Age:27 Name:Bruce
Class:B Age:25 Name:Lucy
作者

Bruce Liu

发布于

2022-11-12

更新于

2022-11-12

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.