流 API - 如何 return 映射唯一任务名称 - 平均结果?
Stream API - how to return map of unique task name - average result?
我有一个CourseResult
class
public class CourseResult {
private final Person person;
private final Map<String, Integer> taskResults; // Here names and results of tasks are saved
public CourseResult(final Person person, final Map<String, Integer> taskResults) {
this.person = person;
this.taskResults = taskResults;
}
public Person getPerson() {
return person;
}
public Map<String, Integer> getTaskResults() {
return taskResults;
}
}
这是我的方法签名
public Map<String, Double> averageScoresPerTask(Stream<CourseResult> programmingResults) {
我需要return每个任务的平均结果。
我将 flatMap
流式传输到 taskResults
' 条目的流,然后使用 Collectors.averagingDouble
获取每个任务的平均值:
public Map<String, Double> averageScoresPerTask(Stream<CourseResult> programmingResults) {
return programmingResults
.flatMap(c -> c.getTaskResults().entrySet().stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)));
}
我有一个CourseResult
class
public class CourseResult {
private final Person person;
private final Map<String, Integer> taskResults; // Here names and results of tasks are saved
public CourseResult(final Person person, final Map<String, Integer> taskResults) {
this.person = person;
this.taskResults = taskResults;
}
public Person getPerson() {
return person;
}
public Map<String, Integer> getTaskResults() {
return taskResults;
}
}
这是我的方法签名
public Map<String, Double> averageScoresPerTask(Stream<CourseResult> programmingResults) {
我需要return每个任务的平均结果。
我将 flatMap
流式传输到 taskResults
' 条目的流,然后使用 Collectors.averagingDouble
获取每个任务的平均值:
public Map<String, Double> averageScoresPerTask(Stream<CourseResult> programmingResults) {
return programmingResults
.flatMap(c -> c.getTaskResults().entrySet().stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.averagingDouble(Map.Entry::getValue)));
}