首页 > 解决方案 > 使用流 api 更新现有函数

问题描述

我有以下方法,我想使用流重写。

我正在考虑编写一个方法并调用它,stream().forEach()但不确定如何映射返回。

List<Student> students  = new ArrayList<>();
        if(myService.getData()!=null){
           for(Person person: myService.getData().getPersons()) {
               Student student = new Student();
               student.setGender(person.getSex());
               student.setGpa(person.getScore);
               students.add(student);
           }
        }

标签: javajava-8java-stream

解决方案


您可以使用Optional然后使用构造函数创建Student对象

public Student(String sex, Integer score)  {
  this.sex = sex;
  this.score = score;
}

然后流式传输Person列表以创建Student

List<Student> students = Optional.ofNullable(myService.getData())
        .map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
        .orElse(Collections.emptyList();

您还可以添加空检查getPersons()

List<Student> students = Optional.ofNullable(myService.getData())
        .filter(data->data.getPersons()!=null)
        .map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
        .orElse(Collections.emptyList();

推荐阅读