gpt4 book ai didi

java - 如何使用 Java 8 lambda 将对象添加到另一个列表内的列表中

转载 作者:行者123 更新时间:2023-11-30 02:27:35 24 4
gpt4 key购买 nike

我对如何使用 Java 8 lambda 将对象添加到另一个列表内的列表有疑问。

让我解释一下:

我有以下对象:

类对象:

public class Course{

private String courseNae;
private List<Student> studentList;

/*gets and sets */

}

学生对象:

public class Student{

private String studentName;
private List<Subject> subjectList;

/*gets and sets */
}

主题对象:

public class Subject{

private String subjectName;
private String details;
private double value;

/*gets and sets */
}

我想这样做,但使用 java 8 lambda:

 for(Class course: this.courseList){
for(Student std: course.getStudentList()){
if(std.getStudentName().equals(name)) {
std.getSubjectList()
.add(Subject.newBuilder()
.subjectName(infoName)
.details("fofofofof")
.value(10.0)
.build());
}
}
}

一般来说: - 我想在我的类(class)列表中找到学生姓名

  • 找到学生姓名后,我想添加新的科目信息在主题列表内。

最佳答案

这可能是解决您问题的一个可能的解决方案:

代码:

courseList.stream()
.map(Course::getStudentList)
.flatMap(Collection::stream)
.filter(student -> student.getStudentName().equals(name))
.findFirst()
.map(Student::getSubjectList)
.ifPresent(subjectList -> subjectList.add(
Subject.newBuilder()
.subjectName(infoName)
.details("fofofofof")
.value(10.0)
.build())
);

说明:

  • .map(Course::getStudentList)将转换输入 List<Course>List<Student> 的流
  • .flatMap(Collection::stream)将展平给定的 List<Student>Student 的流
  • .filter(...)将过滤流,以便仅传输姓名匹配的学生
  • .findFirst()将找到给定流的第一项
  • .map(Student::getSubjectList)现在会将学生流转换为 List<Subject>
  • .ifPresent(...)如果我们找到相应的、匹配的学生,将会被执行

注释:

  • 方法调用如下所示:Course::getStudentList是所谓的方法引用。了解有关它们的更多信息 here .
  • 了解有关流的更多信息 here
  • 了解更多关于 Optional here

关于java - 如何使用 Java 8 lambda 将对象添加到另一个列表内的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com