Search code examples
javajava-streamaverage

Stream API - how to return map of unique task name - average result?


I have a 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;
    }
}

Here is my method signature

public Map<String, Double> averageScoresPerTask(Stream<CourseResult> programmingResults) {

I need to return an average result of every task.


Solution

  • I'd flatMap that stream to a stream of the taskResults' entries, and then use Collectors.averagingDouble to get the average per task:

    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)));
    }