I am learning Java 8 streams and I am trying to refactor a method.
Say I have a School class and a school map that stores all school objects by Id. Each school object contains a student map that stores a bunch of students.
In this scenario, the student Ids are unique across the schools.
I have a function that retrieves a student by the id across all schools.
public Student getStudent(Map<String, School> schoolMap, String studentId) {
return schoolMap.values().stream()
.map(School::getStudentIdToStudentMap)
.filter(map -> map.containsKey(studentId))
.map(map -> map.get(studentId))
.findAny().get();
}
Now, I want to change the function to use schoolId as a filter if available.
public Student getStudent(Map<String, School> schoolMap,
String schoolId /* can be null */,
String studentId)
{
// TODO: Something that I have tried
return schoolMap.get(schoolId)
.getStudentIdToStudentMap()
.get(studentId);
}
Is there a good way I can combine these two functions? If schoolId is null, get the student from all schools. Else just lookup in the particular school and retrieve the student?