
本文介绍了如何使用 Java Stream API,在关联的 User、Movie 和 Score 三张表的数据中,计算电影的平均评分,并找出平均评分最高的 5 部电影,最后按照电影预算进行降序排序。通过示例代码,详细展示了如何利用 Stream API 的 groupingBy、averagingDouble、sorted 和 limit 等操作,实现复杂的数据处理逻辑。
使用 Java Stream 处理多表关联数据并计算平均值排序
在实际开发中,经常会遇到需要从多个关联表中提取数据,进行聚合计算并排序的需求。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免费学习笔记(深入)”;
Listmovies = List.of( new Movie(101, "Mov 1", 200), new Movie(102, "Mov 2", 500), new Movie(103, "Mov 3", 300)); List 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
movieMap = movies.stream() .collect(Collectors.toMap(Movie::id, Function.identity())); -
计算平均评分并排序: 使用 Stream API 对 Score 列表进行处理,计算每个电影的平均评分,并按照评分降序排序,最后取前 5 个。
List
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(); - groupingBy(Score::movieId, Collectors.averagingDouble(Score::score)): 将 Score 按照 movieId 分组,并计算每个电影的平均评分。
- entrySet().stream(): 将 Map 转换为 Stream。
- sorted(Collections.reverseOrder(Entry.comparingByValue())): 按照平均评分降序排序。
- limit(5): 取前 5 个电影。
- map(e -> movieMap.get(e.getKey())): 根据 Movie ID 从 movieMap 中获取 Movie 对象。
- sorted(Collections.reverseOrder(Comparator.comparing(Movie::budget))): 按照电影预算降序排序。
-
输出结果: 将结果打印到控制台。
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 movies = List.of(
new Movie(101, "Mov 1", 200),
new Movie(102, "Mov 2", 500),
new Movie(103, "Mov 3", 300));
List scores = List.of(
new Score(1, 101, 6),
new Score(2, 101, 8),
new Score(1, 102, 6),
new Score(2, 102, 9));
Map movieMap = movies.stream()
.collect(Collectors.toMap(Movie::id, Function.identity()));
List 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);
}
} 注意事项
- 在实际应用中,数据可能来自数据库或其他数据源,需要根据实际情况调整数据读取方式。
- 如果数据量非常大,可以考虑使用并行 Stream 提高处理效率。
- 代码中的 record 是 Java 16 引入的新特性,如果使用较低版本的 Java,需要使用传统的 class 定义数据模型。
总结
本文通过一个具体的例子,展示了如何使用 Java Stream API 处理多表关联数据,并进行复杂的聚合计算和排序。Stream API 的简洁性和强大的功能,可以大大简化代码,提高开发效率。掌握 Stream API 的使用,对于 Java 开发者来说至关重要。










