Java 8 如何使用streams获取父POJO类字段值

Java 8 如何使用streams获取父POJO类字段值,java-8,stream,Java 8,Stream,我有两门课——Student和StudentDetails 我的目标是以Map的形式获取数据 使用流时,无法获取父类(学生)的数据 公共班级学生{ 私有字符串studentName; 私人地图学生详情; 公共地图getStudentDetails(){ 返回学生详细信息; } 公共字符串getStudentName(){ 返回学生姓名; } } 班级学生详情{ 私有字符串subjectName; 私有字符串subjectNo; 公共字符串getFSubjectName(){ 返回subjectN

我有两门课——
Student
StudentDetails

我的目标是以
Map
的形式获取数据

使用流时,无法获取父类(学生)的数据

公共班级学生{
私有字符串studentName;
私人地图学生详情;
公共地图getStudentDetails(){
返回学生详细信息;
}
公共字符串getStudentName(){
返回学生姓名;
}
}
班级学生详情{
私有字符串subjectName;
私有字符串subjectNo;
公共字符串getFSubjectName(){
返回subjectName;
}
公共字符串getSubjectNo(){
返回主题号;
}
}
公共班机{
公共静态void main(字符串[]args){
集合student=null;
Map sts=student.stream()
.map(st->st.getStudentDetails().values())
.flatMap(st->st.stream())
.collect(收集器).groupingBy(学生::getStudentName,
toMap(StudentDetails::getFatherName,StudentDetails::getRollNo));
}
}
错误:Student类型未定义适用于此处的getStudentName(T)

您在执行以下操作时“丢失”了您的学生:

.map(st -> st.getStudentDetails().values())
.flatMap(st -> st.stream()) // this is a Stream<StudentDetails> now
.map(st->st.getStudentDetails().values())
.flatMap(st->st.stream())//这现在是一个流
因此,如果您需要它,只需映射它:

.flatMap(st -> st.getStudentDetails()
                 .values()
                 .stream()
                 .map(sd -> new SimpleEntry<>(st, sd)))
.collect(Collectors.groupingBy(
       en -> en.getKey().getStudentName(),
       Collectors.toMap(
            en -> en.getValue().getFartherName(),
            en -> en.getValue().getRollNo()
       )
))
.flatMap(st->st.getStudentDetails()
.values()
.stream()
.map(sd->new SimpleEntry(st,sd)))
.collect(收集器.groupingBy(
en->en.getKey().getStudentName(),
汤姆(
en->en.getValue().getFartherName(),
en->en.getValue().getRollNo()
)
))
这也可以在没有溪流的情况下完成;您可以尝试查看
Map::compute

.flatMap(st -> st.getStudentDetails()
                 .values()
                 .stream()
                 .map(sd -> new SimpleEntry<>(st, sd)))
.collect(Collectors.groupingBy(
       en -> en.getKey().getStudentName(),
       Collectors.toMap(
            en -> en.getValue().getFartherName(),
            en -> en.getValue().getRollNo()
       )
))