我正在学习 Java 8流,我正在尝试重构一个方法. 假设我有一个学校课程和学校地图,通过Id存储所有学校对象.每个学校对象都包含一个存储一群学生的学生地图. 在这种情况下,学生ID在整个
假设我有一个学校课程和学校地图,通过Id存储所有学校对象.每个学校对象都包含一个存储一群学生的学生地图.
在这种情况下,学生ID在整个学校中是独一无二的.
我有一个功能,可以通过所有学校的id检索学生.
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();
}
现在,我想更改函数以使用schoolId作为过滤器(如果可用).
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);
}
有没有一种方法可以将这两种功能结合起来?如果schoolId为null,请联系所有学校的学生.那么只是在特定的学校查找并找回学生?
我打赌这就是你在找什么:public Student getStudent(Map<String, School> schoolMap, String schoolId, String studentId)
{
return Optional.ofNullable(schoolId) // schoolId might be null
.map(id -> Stream.of(schoolMap.get(id))) // get Stream<School> by else
.orElse(schoolMap.values().stream()) // ... get Stream of all Schools
.flatMap(i -> i.getStudentIdToStudentMap() // students from 1/all schools ...
.entrySet().stream()) // flat map to Stream<Entry<..,..>>
.collect(Collectors.toMap( // collect all entries bu key/value
Entry::getKey, Entry::getValue)) // ... Map<String,Student>
.getOrDefault(studentId, null); // get Student by id or else null
}
您必须在唯一已知的学校或所有学校中搜索.该想法基于搜索过程的共同特征.任何学校的发现都是一样的,无论你是一个已知学校还是所有学校.
或者获取List< Student>来自Optional,
public Student getStudent(Map<String, School> schoolMap, String schoolId, String studentId)
{
return Optional.ofNullable(schoolId) // schoolId might be null
.map(i -> Collections.singletonList(schoolMap.get(i))) // add School into List
.orElse(new ArrayList<>(schoolMap.values())) // ... else all schools
.stream()
.map(i -> i.getStudentIdToStudentMap() // get Map of students from 1/all
.get(studentId)) // ... find by studentId
.filter(Objects::nonNull) // get rid of nulls
.findFirst().orElse(null); // get Student by id or else null
}
