【发布时间】:2021-12-19 18:26:02
【问题描述】:
我想做一个Map<Person, Double>,其中Double 是存储在另一个Map <String, Integer> 中的Integer 值的平均值,这是流元素的字段之一。
public Map<Person,Double> totalScores(Stream<CourseResult> programmingResults) {
return
programmingResults.collect(Collectors.groupingBy(
CourseResult::getPerson,
// And there is a problem, I want to get values from `Map <String, Integer>`
// and do the `averagingInt`, but only get
//`Bad return type in lambda expression:
// Collection<Integer> cannot be converted to int`
Collectors.averagingInt(
s -> s.getTaskResults().values()
)
));
}
我怎样才能以正确的方式获得这些值?
我正在使用一些类:
public class CourseResult {
private final Person person;
private final Map<String, Integer> taskResults;
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;
}
}
【问题讨论】:
-
您必须添加
flatMap才能从逻辑Stream<Collection<Integer>>到Stream<Integer>。不过,需要携带String会增加一些复杂性。 -
同一个
Person真的有多个CourseResult实例,所以需要分组? -
@Holger 实际上没有。每个
Person只有一个CourseResult。 -
那么,
toMap让您的生活更轻松(正如答案现在也指出的那样)。
标签: java lambda type-conversion java-stream