
本文介绍了如何使用 Java Stream API,在关联的 User、Movie 和 Score 三张表的数据中,计算电影的平均评分,并找出平均评分最高的 5 部电影,最后按照电影预算进行降序排序。通过示例代码,详细展示了如何利用 Stream API 的 groupingBy、averagingDouble、sorted 和 limit 等操作,实现复杂的数据处理逻辑。
在实际开发中,经常会遇到需要从多个关联表中提取数据,进行聚合计算并排序的需求。Java Stream API 提供了强大的数据处理能力,可以简洁高效地实现这类复杂操作。以下将以 User、Movie 和 Score 三张表为例,演示如何使用 Java Stream API 计算电影平均评分,并按照评分和预算进行排序。
首先,定义三个数据模型类,分别对应 User、Movie 和 Score 表:
record User(int id, String name) {}
record Movie(int id, String name, int budget) {}
record Score(int userId, int movieId, int score) {}为了方便演示,我们创建一些示例数据:
立即学习“Java免费学习笔记(深入)”;
List<Movie> movies = List.of(
new Movie(101, "Mov 1", 200),
new Movie(102, "Mov 2", 500),
new Movie(103, "Mov 3", 300));
List<Score> scores = List.of(
new Score(1, 101, 6),
new Score(2, 101, 8),
new Score(1, 102, 6),
new Score(2, 102, 9));构建 Movie Map: 将 Movie 列表转换为 Map,方便后续根据 Movie ID 获取 Movie 对象。
Map<Integer, Movie> movieMap = movies.stream()
.collect(Collectors.toMap(Movie::id, Function.identity()));计算平均评分并排序: 使用 Stream API 对 Score 列表进行处理,计算每个电影的平均评分,并按照评分降序排序,最后取前 5 个。
List<Movie> top5 = scores.stream()
.collect(Collectors.groupingBy(
Score::movieId, Collectors.averagingDouble(Score::score)))
.entrySet().stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.limit(5)
.map(e -> movieMap.get(e.getKey()))
.sorted(Collections.reverseOrder(Comparator.comparing(Movie::budget)))
.toList();输出结果: 将结果打印到控制台。
top5.stream().forEach(System.out::println);
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Map.Entry;
public class MovieRanking {
public static void main(String[] args) {
record User(int id, String name) {}
record Movie(int id, String name, int budget) {}
record Score(int userId, int movieId, int score) {}
List<Movie> movies = List.of(
new Movie(101, "Mov 1", 200),
new Movie(102, "Mov 2", 500),
new Movie(103, "Mov 3", 300));
List<Score> scores = List.of(
new Score(1, 101, 6),
new Score(2, 101, 8),
new Score(1, 102, 6),
new Score(2, 102, 9));
Map<Integer, Movie> movieMap = movies.stream()
.collect(Collectors.toMap(Movie::id, Function.identity()));
List<Movie> top5 = scores.stream()
.collect(Collectors.groupingBy(
Score::movieId, Collectors.averagingDouble(Score::score)))
.entrySet().stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.limit(5)
.map(e -> movieMap.get(e.getKey()))
.sorted(Collections.reverseOrder(Comparator.comparing(Movie::budget)))
.toList();
top5.stream().forEach(System.out::println);
}
}本文通过一个具体的例子,展示了如何使用 Java Stream API 处理多表关联数据,并进行复杂的聚合计算和排序。Stream API 的简洁性和强大的功能,可以大大简化代码,提高开发效率。掌握 Stream API 的使用,对于 Java 开发者来说至关重要。
以上就是Java Stream 实现多表关联下的平均值计算与排序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号