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

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

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

    1090 引用 • 3467 回帖 • 298 关注
  • 大神
    6 引用 • 56 回帖
  • list
    10 引用 • 15 回帖
  • Java

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

    3165 引用 • 8206 回帖

相关帖子

欢迎来到这里!

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

注册 关于
请输入回帖内容 ...
  • feix

    😆 咱们和大神的区别估计就在于,大婶在不断的学习吧。 哈哈~

  • 其他回帖
  • someone

    没什么好说的。

  • washmore 1

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

  • feix

    👀 流式计算。有性能比较分析么? 差不离的话 没必要崩溃啊~ 对吧

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