I have three layers and I want to reach students names using streams from Project. I can reach them from Group. How could I do that from Project.
public class Student { private Integer id; private String name; }
public class Group { private Long id; private String groupName; private List<Student> students; }
public class Project { private Long id; private String title; private Integer numberOfGroups; private Integer studentsPerGroup; private List<Group> groups; }
From Group it works fine.
List<Group> groupList = Arrays.asList(new Group(1L, "group#0", list)); for (Group grp : groupList) System.out.println(grp.getStudents().stream().map(Student::getName).collect(toList()));
But when I want do it from Project and run something like this:
List<Project> projects = Arrays.asList(new Project(0L, "Title", 5, 2, groupList)); for (Project prj : projects) System.out.println(prj.getGroups().stream().map(Group::getStudents).map(studentList -> studentList.stream().map(Student::getName).collect(toList())));
I get this: java.util.stream.ReferencePipeline$3@7291c18f
Advertisement
Answer
If I correctly understand your task, you need this stream:
projects.stream() .map(Project::getGroups) .flatMap(Collection::stream) .map(Group::getStudents) .flatMap(Collection::stream) .map(Student::getName) .collect(toList());
With this source List:
List<Project> projects = asList( new Project(0L, "Title", 5, 2, asList( new Group(0L, "", asList( new Student(1, "Smith"), new Student(2, "Jackson"), new Student(3, "Norris") )) ) ) );
I got the output:
[Smith, Jackson, Norris]