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

本贴最后更新于 2914 天前,其中的信息可能已经物是人非

本文是我的代码和大神代码的对比。当大神问我,既然用了 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())

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

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1063 引用 • 3455 回帖 • 153 关注
  • 大神
    6 引用 • 56 回帖
  • list
    10 引用 • 15 回帖
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3201 引用 • 8216 回帖 • 5 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • washmore 1 via macOS

    唔,你需要了解下 jdk8 的核心特性之一:stream
    推荐读物:《java8 函数式编程》

  • 其他回帖
  • ZephyrJung

    @88250 0。0
    @8825O 顺便艾特下高仿号 😆

  • someone

    没什么好说的。

  • ZephyrJung

    就是感觉在大神眼里用个 Java 8 新特性是个很随意的事情
    而我却完全不晓得这个东西的存在

    1 回复
  • 查看全部回帖
ZephyrJung
一切有为法,如梦幻泡影,如露亦如电,应作如是观 北京