使用Java 8 Stream计算学生科目平均分并取最大值的实现
Java 8 Stream 实现代码
import java.util.*; public class StreamCalculateDemo { public static void main(String[] args) { ArrayList<Student> arr = new ArrayList<Student>(); Map<String, Integer> m1 = new HashMap<>(); m1.put("Maths",40); m1.put("Science",50); Map<String, Integer> m2 = new HashMap<>(); m2.put("Maths",60); m2.put("Science",20); arr.add(new Student(m1, "RAJ")); arr.add(new Student(m2, "AMIT")); // 核心计算逻辑 double maxAverage = arr.stream() .mapToDouble(student -> { Map<String, Integer> subjectMarks = student.getSubjectMarks(); // 空值兜底,避免空指针异常 if (subjectMarks == null || subjectMarks.isEmpty()) { return 0.0; } // 计算单个学生的科目平均分 return subjectMarks.values() .stream() .mapToInt(Integer::intValue) .average() .orElse(0.0); }) .max() // 学生列表为空时的兜底默认值 .orElse(0.0); System.out.println("所有学生中的最高平均分为:" + maxAverage); } }
逻辑说明
- 代码完全基于Java 8 Stream链式调用实现,不需要创建额外的中间集合存储每个学生的平均分,内存效率更高
- 内置多层空值保护:覆盖了科目分数Map为空、Map值为null、学生列表为空的常见边界场景,避免运行时抛出异常
- 按照示例数据计算:RAJ的平均分为(40+50)/2=45,AMIT的平均分为(60+20)/2=40,最终输出的最高平均分为45.0
补充:原有代码中用无泛型的原生类型声明Map、使用Spring提供的
HashedMap的写法,可以替换为JDK原生的HashMap<String, Integer>,通过编译期类型校验减少潜在的类型转换错误。
内容的提问来源于stack exchange,提问作者DEV_ANI
相关产品推荐
相关产品推荐

