用例子来学会 Stream
发布时间:2021-12-07 02:06:03 所属栏目:语言 来源:互联网
导读:引言 先从一个例子开始,看看为什么在Java8中要引入流(Stream)? 比如实现这么一个需求:在学生集合中查找男生的数量。 传统的写法为: public long getCountsOfMaleStudent(ListStudent students) { long count = 0; for (Student student : students) { if (
引言 先从一个例子开始,看看为什么在Java8中要引入流(Stream)? 比如实现这么一个需求:在学生集合中查找男生的数量。 传统的写法为: public long getCountsOfMaleStudent(List<Student> students) { long count = 0; for (Student student : students) { if (student.isMale()) { count++; } } return count; } 看似没什么问题,因为我们写过太多类似的**”样板”代码**,尽管智能的IDE通过code template功能让这一枯燥过程变得简化,但终究不能改变冗余代码的本质。 再看看使用流的写法: public long getCountsOfMaleStudent(List<Student> students) { return students.stream().filter(Student::isMale).count(); } 一行代码就把问题解决了! 虽然读者可能还不太熟悉流的语法特性,但这正是函数式编程思想的体现: 回归问题本质,按照心智模型思考问题。 延迟加载。 简化代码。 下面正式进入流的介绍。 (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |