引言
先从一个例子开始,看看为什么在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();
}
一行代码就把问题解决了!
虽然读者可能还不太熟悉流的语法特性,但这正是函数式编程思想的体现:
回归问题本质,按照心智模型思考问题。
延迟加载。
简化代码。
下面正式进入流的介绍。
用例子来学会 Stream
引言 先从一个例子开始,看看为什么在Java8中要引入流(Stream)? 比如实现这么一个需求:在学生集合中查找男生的数量。 传统的写法为: public long getCountsOfMaleStudent(ListStudent students) { long count = 0; for (Student student : students) { if
本文来自网络,不代表站长网立场,转载请注明出处:https://www.tzzz.com.cn/html/biancheng/yuyan/2021/1206/33706.html