How can I calculate average value of duplicate items in List of objects? [on hold]

  • A+
Category:Languages

I have a List of students with their names, grades..

public class Student {         private String name;         private double grade;         /* other fields/getters/setters */  } 

I need to calculate the average grade for all students, but in this List many duplicate names with the different grade, for example:

|   name   |   grade   | ------------------------ | James    |    25     | | Bella    |    41     | | Cort     |    25     | | Bella    |    45     | | Bella    |    21     | | Max      |    43     | | James    |    41     | | Max      |    19     | 

And this is what I want to achieve:

|   name   |   grade   | ------------------------ | James    |    33     | | Bella    |    35.6   | | Cort     |    25     | | Max      |    31     | 

I am not very good at collections, but I am constantly trying to improve my skills, but here I am stacked. I will be glad to any help or tips on how to solve this problem.

 


By using java-streams you can do it easily refer here

  1. Stream the list having Student objects, then
  2. Collect them using groupingBy name as key and average as value

List<Student> list = Arrays.asList(new Student("Bella", 45), new Student("Bella",35));  Map<String, Double> result = list                        .stream()                        .collect(Collectors.groupingBy(Student::getName,                                 Collectors.averagingDouble(Student::getGrade))                        ); System.out.println(result);   //{Bella=40.0} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: