Stream方法使用-peek和foreach方法讲解

简介: Stream方法使用-peek和foreach方法讲解

Stream方法使用

peek和foreach方法

peek 和 foreach ,都可以用于对元素进行遍历然后逐个的进行处理。

但根据前面的介绍(详细可看Stream初相识篇),peek属于中间方法,而foreach属于终止方法。这也就意味着peek只能作为管道中途的一个处理步骤,而没法直接执行得到结果,其后面必须还要有其它终止操作的时候才会被执行;而foreach作为无返回值的终止方法,则可以直接执行相关操作。

publicvoidtestPeekAndforeach() {
List<String>sentences=Arrays.asList("hello world","Jia Gou Wu Dao");
// 演示点1: 仅peek操作,最终不会执行System.out.println("----before peek----");
sentences.stream().peek(sentence->System.out.println(sentence));
System.out.println("----after peek----");
// 演示点2: 仅foreach操作,最终会执行System.out.println("----before foreach----");
sentences.stream().forEach(sentence->System.out.println(sentence));
System.out.println("----after foreach----");
// 演示点3: peek操作后面增加终止操作,peek会执行System.out.println("----before peek and count----");
sentences.stream().peek(sentence->System.out.println(sentence)).count();
System.out.println("----after peek and count----");
}

输出结果可以看出, peek 独自调用时并没有被执行、但peek后面加上终止操作之后便可以被执行,而foreach 可以直接被执行:

----beforepeek--------afterpeek--------beforeforeach----helloworldJiaGouWuDao----afterforeach--------beforepeekandcount----helloworldJiaGouWuDao----afterpeekandcount----
相关文章
|
Java 应用服务中间件 Maven
Spring Boot项目打war包(idea:多种方式)
Spring Boot项目打war包(idea:多种方式)
1173 1
|
Arthas 测试技术
【面试题精讲】JVM-使用Arthas解决线上问题(热部署)
【面试题精讲】JVM-使用Arthas解决线上问题(热部署)
|
SQL 关系型数据库 数据库
学习分布式事务Seata看这一篇就够了,建议收藏
学习分布式事务Seata看这一篇就够了,建议收藏
17333 2
|
Java Spring
required a bean of type ‘org.springframework.web.client.RestTemplate‘ that could not be found.
required a bean of type ‘org.springframework.web.client.RestTemplate‘ that could not be found.
required a bean of type ‘org.springframework.web.client.RestTemplate‘ that could not be found.
|
消息中间件 Java RocketMQ
【RocketMQ系列九】SpringCloudStream整合RocketMQ
【RocketMQ系列九】SpringCloudStream整合RocketMQ
1050 1
|
JSON 前端开发 JavaScript
JSON parse error: Cannot deserialize value of type `java.lang.Integer` from Boolean value
这篇文章讨论了前端Vue应用向后端Spring Boot服务传输数据时发生的类型不匹配问题,即后端期望接收的字段类型为`int`,而前端实际传输的类型为`Boolean`,导致无法反序列化的问题,并提供了问题的诊断和解决方案。
JSON parse error: Cannot deserialize value of type `java.lang.Integer` from Boolean value
|
负载均衡 监控 Java
SpringCloud常见面试题(一):SpringCloud 5大组件,服务注册和发现,nacos与eureka区别,服务雪崩、服务熔断、服务降级,微服务监控
SpringCloud常见面试题(一):SpringCloud 5大组件,服务注册和发现,nacos与eureka区别,服务雪崩、服务熔断、服务降级,微服务监控
23682 7
SpringCloud常见面试题(一):SpringCloud 5大组件,服务注册和发现,nacos与eureka区别,服务雪崩、服务熔断、服务降级,微服务监控
|
存储 消息中间件 JSON
DDD基础教程:一文带你读懂DDD分层架构
DDD基础教程:一文带你读懂DDD分层架构