本文旨在介绍如何利用 Java Stream API,针对多表关联数据,计算平均值并进行排序。通过实际案例,演示如何从用户、电影和评分数据中,找出平均评分最高的 5 部电影,并按照预算进行降序排列。文章将提供详细的代码示例和步骤说明,帮助读者掌握 Java Stream 在复杂数据处理场景下的应用。
在实际应用中,经常会遇到需要关联多个表的数据进行分析和处理的情况。Java Stream API 提供了强大的功能,可以方便地进行数据过滤、转换、聚合和排序。本文将通过一个具体的例子,演示如何使用 Java Stream API,从用户、电影和评分三个表中,找出平均评分最高的 5 部电影,并按照预算进行降序排列。
首先,定义三个数据模型: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) {}接下来,创建一些示例数据,用于演示 Stream API 的使用。
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, 7), new Score(2, 101, 8), new Score(1, 102, 6), new Score(2, 102, 9));
核心逻辑是使用 scores 列表,按照 movieId 进行分组,计算每个电影的平均评分,然后按照平均评分降序排列,最后取前 5 部电影,并按照预算降序排列。
MapmovieMap = 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.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 StreamExample {
record User(int id, String name) {}
record Movie(int id, String name, int budget) {}
record Score(int userId, int movieId, int score) {}
public static void main(String[] args) {
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, 7),
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.forEach(System.out::println);
}
} 本文介绍了如何使用 Java Stream API,针对多表关联数据,计算平均值并进行排序。通过一个具体的例子,演示了如何从用户、电影和评分三个表中,找出平均评分最高的 5 部电影,并按照预算进行降序排列。掌握 Stream API 可以方便地进行数据分析和处理,提高开发效率。