java 懒加载map_详解Java 8中Stream类型的“懒”加载

本文介绍了Java 8 Stream的懒加载特性,强调中间操作的延迟执行和终结操作的执行时机。通过示例展示了如何在查找长度为3的首字母大写的名字时,Stream仅在findFirst()调用时执行过滤和映射操作,从而提高效率。
摘要由CSDN通过智能技术生成

在进入正题之前,我们需要先引入Java 8中Stream类型的两个很重要的操作:

中间和终结操作(Intermediate and Terminal Operation)

Stream类型有两种类型的方法:

中间操作(Intermediate Operation)

终结操作(Terminal Operation)

官方文档给出的描述为[不想看字母的请直接跳过]:

Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce.

Intermediate operationsreturn a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a newstream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

Terminal operations, such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used; if you need to traverse the same data source again, you must return to the data source to get a new stream. In almost all cases, terminal operations are eager, completing their traversal of the data source and processing of the pipeline before returning. Only the terminal operations iterator() and spliterator() are not; these are provided as an &#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值