使用 java 8 流获得最大的平均主题分数



>我有如下班级学生

class Student{
Map<String,Integer> subjectMarks;
String name;


public Student(Map<String,Integer> subject, String name) {
super();
this.subjectMarks = subject;
this.name = name;
}
public Map<String,Integer> getSubjectMarks() {
return subjectMarks;
}
public void setSubjectMarks(Map<String,Integer> subject) {
this.subjectMarks = subject;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

在main方法中,我们在数组列表中添加学生对象,如下所示。

ArrayList<Student> arr = new ArrayList<Student>();
Map m1 = new HashedMap();
m1.put("Maths",40);
m1.put("Science",50);
Map m2 = new HashedMap();
m2.put("Maths",60);
m2.put("Science",20);
arr.add(new Student(m1, "RAJ"));
arr.add(new Student(m2, "AMIT"));

可以帮助/指导我找到每个学生的平均科目分数,然后从 Averge 获得最大值。我需要帮助用java8编写此代码片段

不要将自己限制在 Java 8 中的流的想法中,您必须将流结果直接处理到下一个流中,依此类推......效率可能不是最好的,但请考虑嵌套循环。

开始思考你有什么:每个Student都有几分.您想找到每个Student这些分数的平均值。您可以减少问题,首先考虑如何获得一个Student的平均值。

double average = student.getSubjectMarks().values().stream()
.mapToInt(Integer::valueOf).average().orElse(0.0);

即使您的示例仅显示整数,平均值也可以是浮点数。

然后,您必须遍历所有学生并为每个学生执行上述过程。

Map<String, Double> studentAverages = new HashMap<>();
arr.forEach(student -> {
double average = student.getSubjectMarks().values().stream()
.mapToInt(Integer::valueOf).average().orElse(0.0);
studentAverages.put(student.getName(), average);
});

在所描述的实现中,所需的平均值保存在MapstudentAverages中,该将学生的姓名作为键,将平均值标记为值。

然后,您可以简单地从列表中获取最大整数。

studentAverages.values().stream().mapToDouble(Double::doubleValue).max();

一些答案提供了更复杂的流用法。但是,上面的代码更具可读性。此外,数据类型Object非常笼统,难以进一步使用且容易出错。

正如@Felix在他的回答中指出的那样,由于您有一个嵌套集合,因此很难在单个流中进行处理。您可以使用一个流来计算每个学生的平均值,另一个流来计算平均值的最大值。

从单独的函数开始计算学生的平均值:

private OptionalDouble calculateAverageMarks(Student student) {
return student.getSubjectMarks().values().stream()
.mapToInt(Integer::intValue)
.average();
}

请注意,如果要返回double,可以将.orElse(0.0)(或其他一些值)添加到管道中,但这不允许以后区分全为0的学生和未注册任何科目的学生。

然后,您可以将平均值收集到地图中。

Map<String, OptionalDouble> averageMarks = arr.stream()
.collect(Collectors.toMap(Student::getName, this::calculateAverageMarks));

请注意,如果两个学生共享相同的名称,则在收集器中使用Student::getName将抛出。您可以改用Function.identity()来确保只要您不覆盖Student中的equals,每个键都是不同的。

如果需要,您可以移除没有科目的学生

averageMarks.values().removeIf(v -> !v.isPresent());

在Java 11中,您可以使用OptionalDouble::isEmpty而不是lambda。

然后,您可以将值映射到双流并获得最大值

OptionalDouble max = averageMarks.values().stream()
.filter(OptionalDouble::isPresent) // In case you didn't remove the empty marks
.mapToDouble(OptionalDouble::getAsDouble)
.max();

按照您的要求使用流来解决此问题并没有错。

  • 流式传输地图列表。
  • 将学生的姓名和平均值放在一个对象数组中。
    • 流式传输地图的值并使用摘要统计信息获取平均值。
  • 然后将maxBy与比较器一起使用以获得最大平均值。
  • 然后显示它。
Object[] result = arr.stream().map(s -> new Object[] {
s.getName(),
s.getSubjectMarks().values().stream()
.mapToInt(Integer::valueOf)
.summaryStatistics().getAverage() })
.max(Comparator.comparing(obj -> (double) obj[1]))
.get();
System.out.println(Arrays.toString(result));

指纹

[RAJ, 45.0]

最新更新