本文是我的代码和大神代码的对比。当大神问我,既然用了 Java 8 怎么不这么这么写时,我的内心是崩溃的 😂
我的代码
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())
然而我看着是一脸懵逼。
待查阅相关文档
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于