Java Stream如何高效进行多表关联的平均值计算及排序操作?

2026-05-17 12:431阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1035个文字,预计阅读时间需要5分钟。

Java Stream如何高效进行多表关联的平均值计算及排序操作?

原文:

数据模型定义

首先,我们定义三个数据模型类,分别对应用户(User)、电影(Movie)和评分(Score)表。为了简化示例,我们使用 Java 16 引入的 record 类型:

record User(int id, String name) {} record Movie(int id, String name, int budget) {} record Score(int userId, int movieId, int score) {}

准备测试数据

立即学习“Java免费学习笔记(深入)”;

接下来,准备一些测试数据,用于演示 Stream 操作:

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, 7), new Score(2, 101, 8), new Score(1, 102, 6), new Score(2, 102, 9));

核心 Stream 处理逻辑

现在,我们使用 Java Stream API 实现核心的计算和排序逻辑。首先,将电影列表转换为一个 Map,方便后续根据电影 ID 获取电影信息:

Map<Integer, Movie> movieMap = movies.stream() .collect(Collectors.toMap(Movie::id, Function.identity()));

然后,使用 Stream API 处理评分数据,计算平均评分,筛选前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();

这段代码的详细解释如下:

  1. scores.stream(): 将评分列表转换为 Stream。
  2. .collect(Collectors.groupingBy(Score::movieId, Collectors.averagingDouble(Score::score))): 使用 groupingBy 操作按照 movieId 进行分组,并使用 averagingDouble 操作计算每个电影的平均评分。结果是一个 Map<Integer, Double>,其中 Key 是 movieId,Value 是平均评分。
  3. .entrySet().stream(): 将 Map 转换为 Stream。
  4. .sorted(Collections.reverseOrder(Entry.comparingByValue())): 使用 sorted 操作按照平均评分进行降序排序。Entry.comparingByValue() 用于比较 Map Entry 的 Value(即平均评分)。
  5. .limit(5): 使用 limit 操作限制结果数量为 5,即选择平均评分最高的 5 部电影。
  6. .map(e -> movieMap.get(e.getKey())): 使用 map 操作将 movieId 转换为对应的 Movie 对象。从之前创建的 movieMap 中根据 movieId 获取电影信息。
  7. .sorted(Collections.reverseOrder(Comparator.comparing(Movie::budget))): 使用 sorted 操作按照电影预算进行降序排序。
  8. .toList(): 将 Stream 转换为 List。

输出结果

最后,输出结果:

top5.forEach(System.out::println);

完整的代码示例:

import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.Collections; import java.util.Comparator; import java.util.Map.Entry; public class StreamExample { 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, 7), 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.forEach(System.out::println); } }

注意事项

  • 确保数据模型类正确定义,并且包含必要的字段。
  • 在实际应用中,可能需要处理空指针异常或其他异常情况。
  • 如果数据量很大,可以考虑使用并行 Stream 来提高性能。

总结

本文演示了如何使用 Java Stream API 实现多表关联的复杂数据处理。通过使用 groupingBy、averagingDouble、sorted 和 limit 等 Stream 操作,可以简洁高效地实现各种数据处理需求。这种方法避免了编写复杂的 SQL 查询,提高了代码的可读性和可维护性。

标签:JavaSEOAI

本文共计1035个文字,预计阅读时间需要5分钟。

Java Stream如何高效进行多表关联的平均值计算及排序操作?

原文:

数据模型定义

首先,我们定义三个数据模型类,分别对应用户(User)、电影(Movie)和评分(Score)表。为了简化示例,我们使用 Java 16 引入的 record 类型:

record User(int id, String name) {} record Movie(int id, String name, int budget) {} record Score(int userId, int movieId, int score) {}

准备测试数据

立即学习“Java免费学习笔记(深入)”;

接下来,准备一些测试数据,用于演示 Stream 操作:

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, 7), new Score(2, 101, 8), new Score(1, 102, 6), new Score(2, 102, 9));

核心 Stream 处理逻辑

现在,我们使用 Java Stream API 实现核心的计算和排序逻辑。首先,将电影列表转换为一个 Map,方便后续根据电影 ID 获取电影信息:

Map<Integer, Movie> movieMap = movies.stream() .collect(Collectors.toMap(Movie::id, Function.identity()));

然后,使用 Stream API 处理评分数据,计算平均评分,筛选前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();

这段代码的详细解释如下:

  1. scores.stream(): 将评分列表转换为 Stream。
  2. .collect(Collectors.groupingBy(Score::movieId, Collectors.averagingDouble(Score::score))): 使用 groupingBy 操作按照 movieId 进行分组,并使用 averagingDouble 操作计算每个电影的平均评分。结果是一个 Map<Integer, Double>,其中 Key 是 movieId,Value 是平均评分。
  3. .entrySet().stream(): 将 Map 转换为 Stream。
  4. .sorted(Collections.reverseOrder(Entry.comparingByValue())): 使用 sorted 操作按照平均评分进行降序排序。Entry.comparingByValue() 用于比较 Map Entry 的 Value(即平均评分)。
  5. .limit(5): 使用 limit 操作限制结果数量为 5,即选择平均评分最高的 5 部电影。
  6. .map(e -> movieMap.get(e.getKey())): 使用 map 操作将 movieId 转换为对应的 Movie 对象。从之前创建的 movieMap 中根据 movieId 获取电影信息。
  7. .sorted(Collections.reverseOrder(Comparator.comparing(Movie::budget))): 使用 sorted 操作按照电影预算进行降序排序。
  8. .toList(): 将 Stream 转换为 List。

输出结果

最后,输出结果:

top5.forEach(System.out::println);

完整的代码示例:

import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.Collections; import java.util.Comparator; import java.util.Map.Entry; public class StreamExample { 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, 7), 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.forEach(System.out::println); } }

注意事项

  • 确保数据模型类正确定义,并且包含必要的字段。
  • 在实际应用中,可能需要处理空指针异常或其他异常情况。
  • 如果数据量很大,可以考虑使用并行 Stream 来提高性能。

总结

本文演示了如何使用 Java Stream API 实现多表关联的复杂数据处理。通过使用 groupingBy、averagingDouble、sorted 和 limit 等 Stream 操作,可以简洁高效地实现各种数据处理需求。这种方法避免了编写复杂的 SQL 查询,提高了代码的可读性和可维护性。

标签:JavaSEOAI