【问题标题】:How to add object into a list inside of the other list using Java 8 lambdas如何使用 Java 8 lambda 将对象添加到另一个列表中的列表中
【发布时间】:2017-07-21 12:43:37
【问题描述】:

我对如何使用 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());
            }
        }
    }

一般来说: - 我想在我的课程列表中找到学生姓名

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

【问题讨论】:

  • 你尝试过...?
  • 这个词是 student,不是 studant。而class 不是有效的变量名。
  • 定义Class 类也不是一个好主意,我建议改用Course
  • 我更改了我的帖子,感谢您的反馈
  • 您好,请展示一下使用流 API 的努力。请求从命令式到函数式和流式的翻译似乎并不是获得正确答案的最佳方法。做一些研究,尝试一些事情,如果遇到困难,请在这里提问。

标签: java lambda java-8 java-stream


【解决方案1】:

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

代码:

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&lt;Course&gt; 转换为 List&lt;Student&gt; 的流
  • .flatMap(Collection::stream) 会将给定的List&lt;Student&gt; 展平为Student 的流
  • .filter(...) 将过滤流,以便仅流式传输具有匹配名称的学生
  • .findFirst() 将找到给定流的第一项
  • .map(Student::getSubjectList) 现在会将学生流转换为 List&lt;Subject&gt;
  • .ifPresent(...) 将在我们找到匹配的学生时执行

注意事项:

  • 看起来像这样的方法调用:Course::getStudentList 是所谓的方法引用。阅读更多关于他们的信息here
  • 阅读更多关于流的信息here
  • 阅读更多关于Optionalhere

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-08-06
    • 1970-01-01
    • 2021-10-05
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多