springboot写一个stream api接口
以下是一个使用Spring Boot和Stream API的示例接口:
@RestController
@RequestMapping("/students")
public class StudentController {
private List<Student> students = Arrays.asList(
new Student("Tom", "Math", 87),
new Student("Alice", "English", 92),
new Student("Bob", "Math", 78),
new Student("David", "History", 85),
new Student("Emily", "English", 90),
new Student("Frank", "Math", 80)
);
@GetMapping("/averageScore/{subject}")
public double getAverageScoreBySubject(@PathVariable String subject) {
return students.stream()
.filter(s -> s.getSubject().equals(subject))
.mapToDouble(Student::getScore)
.average()
.orElse(0.0);
}
@GetMapping("/highestScore/{subject}")
public Student getHighestScoreBySubject(@PathVariable String subject) {
return students.stream()
.filter(s -> s.getSubject().equals(subject))
.max(Comparator.comparing(Student::getScore))
.orElse(null);
}
@GetMapping("/topStudents")
public List<Student> getTopStudents() {
return students.stream()
.sorted(Comparator.comparing(Student::getScore).reversed())
.limit(3)
.collect(Collectors.toList());
}
// Other endpoints...
}
该示例使用了Java 8的Stream API来对学生对象进行过滤、排序和聚合。其中:
getAverageScoreBySubject方法接受一个参数subject,返回选修该学科的学生的平均分数。getHighestScoreBySubject方法接受一个参数subject,返回选修该学科的学生中分数最高的学生。getTopStudents方法返回分数最高的三个学生。
在这个示例中,我们可以看到Stream API的强大之处,它可以让代码更简洁、更易读,并且能够更好地利用现代计算机的多核心和并行计算能力。
原文地址: http://www.cveoy.top/t/topic/bnkO 著作权归作者所有。请勿转载和采集!