一 Stream流操作-count
Java程序员在使用集合类时,一个通用的模式是在集合上进行迭代,然后处理返回的每一
个元素。比如要计算年龄大于或等于20岁的人数
package yqq.Lambda.Stream.Count;
import java.util.ArrayList;
import java.util.List;
/**
* @Author yqq
* @Date 2021/4/10 22:20
* @Version 1.0
*/
public class CountDemo {
public static void main(String[] args) {
List<People> peopleList=new ArrayList<People>();
peopleList.add(new People("1","yqq1",19));
peopleList.add(new People("2","yqq2",20));
peopleList.add(new People("3","yqq3",21));
peopleList.add(new People("4","yqq4",22));
//《例1》使用for循环计算年龄大于或等于20岁的人数
int count=0;
for(People people:peopleList){
if(people.getAge()>=20){
count++;
}
}
System.out.println("年龄大于或等于20岁的人数为:"+count);
//《例2》使用Stream 流计算年龄大于或等于20岁的人数
Long sum=peopleList.stream()
.filter(p -> p.getAge()>=20)
.count();
System.out.println("年龄大于或等于20岁的人数为:"+sum);
}
}
//年龄大于或等于20岁的人数为:3
1.Stream是用函数式编程方式在集合类上进行复杂操作的工具。
由于StreamAPI的函数式编程风格,我们并没有改变集合的内容,而是描述出Stream里的内容。count()方法计给
定Stream里包含多少个对象。
1.惰性求值方法
例:只过滤,不计数
allArtists.stream()
.filter(artist->artist.isFrom(“London”));
这行代码并未做什么实际性的工作,filter只刻画出了Stream,但没有产生新的集合。像
filter这样只描述Stream,最终不产生新集合的方法叫作惰性求值方法;
2.及早求值方法
而像count这样最终会从Stream产生值的方法叫作及早求值方法。