我与大神——集合类型转换

本文是我的代码和大神代码的对比。当大神问我,既然用了Java 8 怎么不这么这么写时,我的内心是崩溃的 :joy:

我的代码

public List<Student> getStudentByName(String name) {
    List<People> peoples = peopleService.getPeopleByName(name);
    List<Student> students = new ArrayList<>();
    for(People people : peoples){
        Student student = new Student();
        students.add(convertStudent(people));
    }
    return students;
}
private Student convertStudent(People people){
    if(people == null){
        return null;
    }
    Student student = new Student();
    student.setName(people.getName());
    student.setClass("三年二班");
    return student;
}

大神的代码

public List<Student> getStudentByName(String name) {
    List<People> peoples = peopleService.getPeopleByName(name);
    return peoples.stream().map(this::convertStudent).collect(Collectors.toList());
}
private Student convertStudent(People people){
    if(people == null){
        return null;
    }
    Student student = new Student();
    student.setName(people.getName());
    student.setClass("三年二班");
    return student;
}

主要区别

大神用一行代码替换了我的for循环:

peoples.stream().map(this::convertStudent).collect(Collectors.toList())

然而我看着是一脸懵逼。
待查阅相关文档

validate