java8流库之Stream.iterate

news2024/10/6 20:28:48

简介

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;

        @Override
        public 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;

        @Override
        public 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;
        }

        @Override
        public 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.coloradmin.cn/o/1326335.html

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

相关文章

跟着野火学FreeRTOS:第一段(空闲任务与阻塞延时的实现)

在前一小节中&#xff0c;任务操作里面的延时就是直接让 C P U CPU CPU干等着&#xff0c;啥也不干&#xff0c;这样会极大的浪费 C P U CPU CPU的资源。这一小节即将要讲到的阻塞延时就是当任务有延时需要的时候让 C P U CPU CPU不要干等着&#xff0c;而是去执行其它的任务&a…

取消paypal免密支付绑定平台

在设置支付中-》自动支付-》取消特定平台即可。

随机森林 2(决策树)

通过 随机森林 1 的介绍&#xff0c;相信大家对随机森林都有了一个初步的认知&#xff0c;知道了随机和森林分别指的是什么&#xff0c;以及决策树根据什么选择内部节点。本文将会从森林深入到树&#xff0c;去看一下决策树是如何构建的。网上很多文章都讲了决策树如何构建&…

【已解决】解决Springboot项目访问本地图片等静态资源无法访问的问题

今天在开发一个招聘系统的时候&#xff0c;有投递简历功能&#xff0c;有投递就会有随之而来的查看简历对吧&#xff0c;我投递过的简历&#xff0c;另存为一个文件夹&#xff0c;就是说本地磁盘(或者服务器)有一个专门存放投递过的简历的文件夹&#xff0c;用于存放PDF&#x…

用户管理第2节课--idea 2023.2 后端--实现基本数据库操作(操作user表)

一、模型user对象>和数据库的字段关联 & 自动生成 【其中涉及删除表数据&#xff0c;一切又从零开始】 二、模型user对象>和数据库的字段关联 2.1在model文件夹下&#xff0c;新建 user对象 2.1.1 概念 大家可以想象我们现在的数据是存储在数据库里的&…

Java中的时间日期类⭐️通过具体案例分析下开发中常用到的几种时间日期格式类的使用

小伙伴们大家好&#xff0c;系统中不少模块都要用到时间日期&#xff0c;来分析总结下项目中用到的些日期类 目录 一、时间日期类 1.java.util.Calendar&#xff1a; 2.java.util.Date&#xff1a; 3.java.time.LocalDate、java.time.LocalTime、java.time.LocalDateTime&…

Ubuntu 常用命令之 netstat 命令用法介绍

&#x1f4d1;Linux/Ubuntu 常用命令归类整理 netstat 是一个非常有用的命令行工具&#xff0c;它可以帮助我们监控和诊断网络问题。在 Ubuntu 系统中&#xff0c;我们可以使用 netstat 命令来查看网络连接、路由表、接口统计等信息。 netstat 命令的参数有很多&#xff0c;以…

anaconda 安装 使用 pytorch onnx onnxruntime

一&#xff1a;安装 如果不是 x86_64&#xff0c;需要去镜像看对应的版本 安装 Anaconda 输入命令 bash Anaconda3-2021.11-Linux-x86_64.sh 然后输入 yes 表示同意 确认安装的路径&#xff0c;一般直接回车安装在默认的 /home/你的名字/anaconda3 很快就安装完毕。输入 yes…

【Vue中给输入框加入js验证_blur失去焦点进行校验】

【Vue中给输入框加入js验证_blur失去焦点进行校验】 通俗一点就是给输入框加个光标离开当前文本输入框时&#xff0c;然后对当前文本框内容进行校验判断 具体如下&#xff1a; 1.先给文本框加属性 blur“validatePhoneNumber” <el-input v-model“entity.telephone” blur…

航空港务数据大屏为航空港的可持续发展提供有力支撑!

随着经济的发展&#xff0c;不断加建与扩建民用机场&#xff0c;空港行业规模不断扩大。在不断引进和消化发达国家先进技术的同时&#xff0c;中国深入开展了对新技术和新材料的研究&#xff0c;极大地丰富和发展了中国的机场建设技术。且各项机场建设计划均已落实推进&#xf…

下午好~ 我的论文【yolov5】(第四期)

文章目录 简介模型Mosaic数据增强自适应锚框计算自适应图片缩放Focus结构CSP结构 NeckCIOU_Lossnms非极大值抑制代码最后 简介 YOLO V4没过多久YOLO V5就出来了。YOLO V5的模型架构是与V4非常相近的。 模型 Yolov5官方代码中&#xff0c;给出的目标检测网络中一共有4个版本&…

列举mfc140u.dll丢失的解决方法,常见的mfc140u.dll问题

在使用电脑的过程中&#xff0c;有时会遇到mfc140u.dll文件丢失的问题&#xff0c;导致一些应用程序无法正常启动。本文将介绍mfc140u.dll丢失的常见原因&#xff0c;并提供相应的解决办法。同时&#xff0c;还会列举一些与mfc140u.dll丢失相关的常见问题和解答。 第一部分&…

基于FPGA的简易BPSK和QPSK

1、框图 2、顶层 3、m_generator M序列的生成&#xff0c;输出速率为500Kbps 4、S2P是串并转换模块 将1bit的m序列转换到50M时钟下的2bit M序列数据&#xff08;就有4个象限&#xff09;&#xff1b; 5、my_pll是生成256M的时钟作为载波&#xff0c;因为sin和cos信号的…

数据管理平台Splunk Enterprise本地部署结合内网穿透实现远程访问

文章目录 前言1. 搭建Splunk Enterprise2. windows 安装 cpolar3. 创建Splunk Enterprise公网访问地址4. 远程访问Splunk Enterprise服务5. 固定远程地址 前言 Splunk Enterprise是一个强大的机器数据管理平台&#xff0c;可帮助客户分析和搜索数据&#xff0c;以及可视化数据…

汽车大灯led恒流驱动芯片OC5501 可高低亮调光

LED恒流驱动芯片是一种在汽车大灯中常见的关键部件。它能提供稳定的电流&#xff0c;使LED灯光亮度均匀、稳定&#xff0c;并且延长LED的寿命。 传统的汽车大灯使用的是卤素灯泡&#xff0c;而现在越来越多的汽车厂商开始使用LED大灯。LED大灯具有更好的能效和更长的寿命&…

08 Vue3中的v-text指令

概述 v-text指令主要是用来渲染文本内容&#xff0c;和双大括号的效果基本一致&#xff0c;所以使用场景非常少。 一般情况下&#xff0c;我们都会使用双大括号语法去渲染文本内容&#xff0c;而不是使用v-text指令。 基本用法 我们创建src/components/Demo08.vue&#xff…

【超图】SuperMap iClient3D for WebGL/WebGPU ——颜色(1)

作者&#xff1a;taco 在项目中通常会出现&#xff0c;高亮对象。给对象设置颜色的一些问题。那么针对颜色设置在超图的 iClient3D for WebGl/WebGPU 中又提供了哪些方式呢&#xff1f;本篇文章将介绍一些颜色的设置方法。以及一些颜色的参数设置。 在iClient3D for WebGl/WebG…

ChimeraX使用教程-安装及基本操作

ChimeraX使用教程-安装及基本操作 1、访问https://www.cgl.ucsf.edu/chimerax/download.html进行下载&#xff0c;然后安装 安装完成后&#xff0c;显示界面 2、基本操作 1、点击file&#xff0c;导入 .PDB 文件。 &#xff08;注&#xff1a;在 alphafold在线预测蛋白》点…

比特币和区块链并非游离在法律之外

​​发表时间&#xff1a;2023年12月01日 近年来&#xff0c;围绕区块链监管的讨论&#xff0c;已经成为政策制定者、行业领袖和区块链爱好者之间越来越重要的话题。随着各国政府在促进创新和确保消费者保护之间寻求着平衡&#xff0c;有关区块链监管的持续讨论反映出这项变革性…

Ansible的脚本---Playbook剧本编写

playbook的组成部分 1、 tasks&#xff1a;任务 在目标主机上需要执行的操作。使用模块定义这些操作。每个任务都是一个模块的调用。 2、 variables&#xff1a;变量 用于存储和传递数据。类似于shell脚本中的变量。变量可以自定义。可以在playbook当中定义为全局变量&…