Skip to content
Advertisement

Java streams average

I need to create two methods using streams. A method that returns an average score of each task.

JavaScript

and a method that returns a task with the highest average score.

JavaScript

I can only modify those 2 methods.

Here is CourseResult class

JavaScript

And methods that create CourseResult objects.

JavaScript

Based on these methods I can calculate an average of each task by dividing sum of scores of this task by 3, because there are only 3 Persons tho I can make it so it divides by a number equal to number of CourseResult objects in a stream if these methods get their .limit(3) changed. I don’t know how to access keys of taskResults Map. I think I need them to then return a map of unique keys. A value for each unique key should be an average of values from taskResults map assigend to those keys.

Advertisement

Answer

For your first question: map each CourseResult to taskResults, flatmap to get all entries of each taskResults map form all CourseResults, group by map keys (task names) and collect averaging the values for same keys:

JavaScript

You can use the same approach for your second question to calculate the average for each task and finaly stream over the entries of the resulting map to find the task with the highest average.

JavaScript

To avoid code duplication you can call the first method within the second:

JavaScript

EDIT

To customize the calculation of the average regardless how many items your maps contain, don’t use the inbuilt operations like Collectors.averagingInt or Collectors.averagingDouble. Instead wrap your collector in collectingAndThen and sum the scores using Collectors.summingInt and finally after collecting divide using a divisor according if the task name starts with Lab or not:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement