for toy example, have list of classrooms id , name. fetch these classrooms datasource , then, each classroom, need students , teacher lists fetched. create object takes in classroom.id, classroom.name , list<student>, list<teacher>
called foo. issue being foo immutable object , must instantiated when info available. here have tried:
list<classroom> classrooms = datasource.fetchclassroomsbyid(classroomids); map<integer, classroom> idtoclassroom = new hashmap<>(); classrooms.stream() .foreach(classroom -> {idtoclassroom.put(classroom.getid(), classroom);}); //get students , teachers belong set of classroomids passed in list<student> students = datasource.fetchstudentsbyid(classroomids); list<teacher> teachers = datasource.fetchteachersbyid(classroomids); (student student : students) { //gets classroom student belongs. stuck. idstoclassroom.get(student.getclassroomid()) } ...
basically, how can construct foo object efficiently , compactly @ point?
use collectors.groupingby
group students , teachers in lists of same classroom id.
list<classroom> classrooms = datasource.fetchclassroomsbyid(classroomids); list<student> students = datasource.fetchstudentsbyid(classroomids); list<teacher> teachers = datasource.fetchteachersbyid(classroomids); map<integer, list<student>> classroomidtostudent = students.stream() .collect(collectors.groupingby(student::getclassroomid)); map<integer, list<teacher>> classroomidtoteacher = teachers.stream() .collect(collectors.groupingby(teacher::getclassroomid)); list<foo> foos = classrooms.stream().map(c -> new foo(c.getid(), c.getname(), classroomidtostudent.get(c.getid()), classroomidtoteacher.get(c.getid()))).collect(collectors.tolist());
Comments
Post a Comment