您的位置:首页 >Java Stream 多表关联平均值计算与排序方法
发布于2025-11-30 阅读(0)
扫一扫,手机访问

本文介绍了如何使用 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) {}为了方便演示,我们创建一些示例数据:
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 开发者来说至关重要。
上一篇:Edge浏览器主页设置教程
下一篇:拼多多跨境商品支持仅退款吗?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9