J H
J H

Reputation: 25

Java streams - getting a map from list of maps

I have a class University that contains (among other things) a list of semesters and a method: public Map<String,Integer> gradesMap(Student s,Semester s) that should return a map of grades for a given student in a given semester. Classes Semester and Course look something like this:

public class Semester{
...
private List<Course> courses;
public List<Courses> getCourses(){return courses;}
...
}

public class Course{
...
String courseName;
private Map<Student,Integer> courseGrades;

public Map<Student,Integer> getCourseGrades(){return courseGrades;}
public String getCourseName(){return courseName;}
...
}

I tried writing something like:

Map<String,Integer> grades=semester.getCourses().stream().
forEach(c->c.getCourseGrades()).collect(Collectors.toMap(key,value));

but I'm not sure how to fetch the key and value for my map. Any suggestions would be appreciated.

Edit: Output map should contain a Course name and a grade.

Upvotes: 2

Views: 96

Answers (1)

Eklavya
Eklavya

Reputation: 18410

You can get the course grade from the Course Grade map by the student and collect grade as the map's value and course name as the key.

Map<String,Integer> gradesMap = 
       semester.getCourses()
               .stream()
               .collect(Collectors.toMap(c -> c.getName(),
                                         c -> c.getCourseGrades().get(studentObj)));

Note: Make sure you defined equals() and hashCode() for Student

Upvotes: 1

Related Questions