java8流库之Stream.iterate

简介

java.util.stream.Stream 下共有两个 iterate

  • iterate(T seed, final UnaryOperator<T> f)
  • iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> f)

该方法产生一个无限流,它的元素包含seed,在seed上调用f产生的值、在前一个元素上调用f产生的值,等等。

第一个方法会产生一个无限流,而第二个方法的流会在碰到第一个不满足hasNext谓词的元素时终止

两个参数

/*** Returns an infinite sequential ordered {@code Stream} produced by iterative* application of a function {@code f} to an initial element {@code seed},* producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},* {@code f(f(seed))}, etc.** <p>The first element (position {@code 0}) in the {@code Stream} will be* the provided {@code seed}.  For {@code n > 0}, the element at position* {@code n}, will be the result of applying the function {@code f} to the* element at position {@code n - 1}.** <p>The action of applying {@code f} for one element* <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>* the action of applying {@code f} for subsequent elements.  For any given* element the action may be performed in whatever thread the library* chooses.** @param <T> the type of stream elements* @param seed the initial element* @param f a function to be applied to the previous element to produce*          a new element* @return a new sequential {@code Stream}*/
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {Objects.requireNonNull(f);Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,Spliterator.ORDERED | Spliterator.IMMUTABLE) {T prev;boolean started;@Overridepublic boolean tryAdvance(Consumer<? super T> action) {Objects.requireNonNull(action);T t;if (started)t = f.apply(prev);else {t = seed;started = true;}action.accept(prev = t);return true;}};return StreamSupport.stream(spliterator, false);
}

三个参数

/*** Returns a sequential ordered {@code Stream} produced by iterative* application of the given {@code next} function to an initial element,* conditioned on satisfying the given {@code hasNext} predicate.  The* stream terminates as soon as the {@code hasNext} predicate returns false.** <p>{@code Stream.iterate} should produce the same sequence of elements as* produced by the corresponding for-loop:* <pre>{@code*     for (T index=seed; hasNext.test(index); index = next.apply(index)) {*         ...*     }* }</pre>** <p>The resulting sequence may be empty if the {@code hasNext} predicate* does not hold on the seed value.  Otherwise the first element will be the* supplied {@code seed} value, the next element (if present) will be the* result of applying the {@code next} function to the {@code seed} value,* and so on iteratively until the {@code hasNext} predicate indicates that* the stream should terminate.** <p>The action of applying the {@code hasNext} predicate to an element* <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>* the action of applying the {@code next} function to that element.  The* action of applying the {@code next} function for one element* <i>happens-before</i> the action of applying the {@code hasNext}* predicate for subsequent elements.  For any given element an action may* be performed in whatever thread the library chooses.** @param <T> the type of stream elements* @param seed the initial element* @param hasNext a predicate to apply to elements to determine when the*                stream must terminate.* @param next a function to be applied to the previous element to produce*             a new element* @return a new sequential {@code Stream}* @since 9*/
public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) {Objects.requireNonNull(next);Objects.requireNonNull(hasNext);Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,Spliterator.ORDERED | Spliterator.IMMUTABLE) {T prev;boolean started, finished;@Overridepublic boolean tryAdvance(Consumer<? super T> action) {Objects.requireNonNull(action);if (finished)return false;T t;if (started)t = next.apply(prev);else {t = seed;started = true;}if (!hasNext.test(t)) {prev = null;finished = true;return false;}action.accept(prev = t);return true;}@Overridepublic void forEachRemaining(Consumer<? super T> action) {Objects.requireNonNull(action);if (finished)return;finished = true;T t = started ? next.apply(prev) : seed;prev = null;while (hasNext.test(t)) {action.accept(t);t = next.apply(t);}}};return StreamSupport.stream(spliterator, false);
}

示例

public static  void main(String args[]) throws IOException {Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));show("integers", integers);System.out.println("end");}public static <T> void show(String title, Stream<T> stream) {final int SIZE = 10;List<T> firstElements = stream.limit(SIZE + 1).collect(Collectors.toList());System.out.println(title + ":");for (int i = 0; i < firstElements.size(); i++) {if (i > 0) System.out.println(",");if (i < SIZE) System.out.println(firstElements.get(i));else System.out.println("……");}System.out.println();
}

在执行 Stream.iterate 时并没有生成具体数据,只是产生了一个流,只有在使用时才会有数据

流和集合的区别

  1. 流并不存储其元素。这些元素可能存储在底层的集合中,或者是按需生成的
  2. 流的操作不会修改其数据源。例如 filter方法不会从流中移除元素,而是会生成一个新的流,其中不包含被过滤掉的元素
  3. 流的操作是尽可能惰性执行的。这意味着直至需要其结果时,操作才会执行。例如,如果我们只想查询前5个长单词而不是所有长单词,那么filter方法就会在匹配到第5个单词后停止过滤。因此,我们甚至可以操作无限流(上边的示例就是一个操作无限流的例子)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/237204.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Matlab论文插图绘制模板第131期—函数等高线图

在之前的文章中&#xff0c;分享了Matlab函数折线图的绘制模板&#xff1a; 函数三维折线图&#xff1a; 函数网格曲面图&#xff1a; 函数曲面图&#xff1a; 进一步&#xff0c;再来分享一下函数等高线图。 先来看一下成品效果&#xff1a; 特别提示&#xff1a;本期内容『数…

【Week-P2】CNN彩色图片分类-CIFAR10数据集

文章目录 一、环境配置二、准备数据三、搭建网络结构四、开始训练五、查看训练结果六、总结3.1 ⭐ torch.nn.Conv2d()详解3.2 ⭐ torch.nn.Linear()详解3.3 ⭐torch.nn.MaxPool2d()详解3.4 ⭐ 关于卷积层、池化层的计算4.2.1 optimizer.zero_grad()说明4.2.2 loss.backward()说…

MyBatis Plus使用遇到的问题

如果想使用Mapper的xxxById()方法&#xff0c;实体类的主键上面必须加上TableId注解&#xff0c;如果不加&#xff0c;会报错 2023-12-21 22:48:33.526 WARN 11212 --- [ main] c.b.m.core.injector.DefaultSqlInjector : class com.example.mybatisplusdemo.dom…

ubuntu18.04 64 位安装笔记——备赛笔记——2024全国职业院校技能大赛“大数据应用开发”赛项——任务2:离线数据处理

进入VirtuakBox官网&#xff0c;网址链接&#xff1a;Oracle VM VirtualBoxhttps://www.virtualbox.org/ 网页连接&#xff1a;Ubuntu Virtual Machine Images for VirtualBox and VMwarehttps://www.osboxes.org/ubuntu/ 将下发的ds_db01.sql数据库文件放置mysql中 12、编写S…

无约束优化问题求解笔记(2):最速下降法

目录 3. 最速下降法3.1 最速下降法的基本思想3.2 基于精确搜索的最速下降法3.3 基于精确搜索的最速下降法的程序实现3.4 基于精确搜索的最速下降法的缺点 Reference 3. 最速下降法 3.1 最速下降法的基本思想 最速下降法是典型的线搜索方法. 设 f f f 是 R n \mathbb{R}^n R…

vue2与vue3的区别

首先了解什么是vue3 Vue.js 3.0&#xff08;简称Vue 3&#xff09;是一个流行的JavaScript框架Vue.js的最新版本。Vue 3于2020年9月正式发布&#xff0c;带来了许多令人兴奋的新特性和改进。下面是Vue 3的一些主要特点&#xff1a; 更快的性能&#xff1a;Vue 3通过全新的响应…

【redis】redis系统实现发布订阅的标准模板

目录 简介参数配置代码模板 简介 Redis发布订阅功能是Redis的一种消息传递模式&#xff0c;允许多个客户端之间通过消息通道进行实时的消息传递。在发布订阅模式下&#xff0c;消息的发送者被称为发布者&#xff08;publisher&#xff09;&#xff0c;而接收消息的客户端被称为…

Easyexcel读取单/多sheet页

Easyexcel读取单/多sheet页 此文档会说明单个和多个的sheet页的读取方法&#xff0c;包括本人在使用过程中的踩坑点。 依赖不会的自行百度导入&#xff0c;话不多说&#xff0c;直接上干货。以下示例基于2.x&#xff0c;新版本基本类似 1、创建实体 实体是用来接收对应列的数据…

【QT】QGraphicsView和QGraphicsItem坐标转换

坐标转换 QGraphicsItem和QGraphicsView之间的坐标转换需要通过QGraphicsScene进行转换 QGraphicsView::mapToScene() - 视图 -> 场景QGraphicsView::mapFromScene() - 场景 -> 视图QGraphicsItem::mapToScene() - 图元 -> 场景QGraphicsItem::mapFromScene() - 场景 …

java连接oracle出现ORA-12505错误

问题 sqlplus可以连接;但java连接报错:ORA-12505 ORA-12505, TNS:listener does not currently know of SID given in connect descr 解析 原因: 数据库中实际使用的实例名并非与集群对外使用的相同&#xff0c;使用第三方构件或程序进行连接的时候&#xff0c;所给数据库运…

Arduino驱动LTR390-UV紫外线传感器(光照传感器篇)

目录 1、传感器特性 2、硬件原理图 3、控制器和传感器连线图 4、驱动程序

C++ Qt开发:StringListModel字符串列表映射组件

Qt 是一个跨平台C图形界面开发库&#xff0c;利用Qt可以快速开发跨平台窗体应用程序&#xff0c;在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置&#xff0c;实现图形化开发极大的方便了开发效率&#xff0c;本章将重点介绍QStringListModel字符串映射组件的常用方法及…

Java-JDBC(重要)--待更新

1、第一个JDBC程序 步骤总结&#xff1a; 创建测试数据库加载驱动&#xff0c;固定写法连接数据库获得执行SQL的对象statement执行SQL对象去执行SQLresultset获得返回结果集释放连接 import java.sql.*;public class Jdbc {public static void main(String args[]) throws C…

线程(四)

线程(一) ~ 线程(四)章节导图 导图https://naotu.baidu.com/file/07f437ff6bc3fa7939e171b00f133e17 线程安全 什么是线程安全&#xff1f; 业务中多线程同时访问一个对象或方法时我们不需要做额外的处理&#xff08;像单线程编程一样&#xff09;程序可以正常运行并能获取…

11_12-Golang中的运算符

**Golang **中的运算符 主讲教师&#xff1a;&#xff08;大地&#xff09; 合作网站&#xff1a;www.itying.com** **&#xff08;IT 营&#xff09; 我的专栏&#xff1a;https://www.itying.com/category-79-b0.html 1、Golang 内置的运算符 算术运算符关系运算符逻辑运…

JS模块化规范之ES6及UMD

JS模块化规范之ES6及总结 前言ES6模块化概念基本使用ES6实现 UMD(Universal Module Definition)总结 前言 ESM在模块之间的依赖关系是高度确定的&#xff0c;与运行状态无关&#xff0c;编译工具只需要对ESM模块做静态分析&#xff0c;就可以从代码字面中推断出哪些模块值未曾被…

RocketMQ系统性学习-RocketMQ原理分析之Broker接收消息的处理流程

&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308;&#x1f308; 【11来了】文章导读地址&#xff1a;点击查看文章导读&#xff01; &#x1f341;&#x1f341;&#x1f341;&#x1f341;&#x1f341;&#x1f341;&#x1f3…

Leetcode 53 最大子数组和

题意理解&#xff1a; 给定一个数列&#xff0c;求连续的子序列的和最大可以是多少&#xff1f; 子数组 是数组中的一个连续部分。 比如&#xff1a; nums [-2,1,-3,4,-1,2,1,-5,4] 最大子序列的和&#xff1a;6&#xff08;4-121&#xff09; 解题思路&#xff1a; 使用贪心的…

回溯法之计算操作符

问题: 设计一个算法在 1&#xff0c;2&#xff0c;……9(顺序不变)数值之间插入或者-或者什么都不插入&#xff0c; 使得计算结果总是 100 的程序。 //例如 1 2 34 - 5 67 - 8 9 100。 思路: 创建一个长度为9的数组arr&#xff0c;其中存放数字1到9。创建一个长度为9的字…

【git学习笔记 01】打标签

文章目录 一、声明二、对标签的基本认知什么是标签&#xff1f;为什么要打标签&#xff1f;如何生成类似github中readme的图标 三、标签相关命令四、示例操作 一、声明 本帖持续更新中如有纰漏&#xff0c;望批评指正&#xff01;参考视频链接&#xff0c;非常感谢原作者&…