Stream.iterate方法与UnaryOperator

Posted nyfor2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream.iterate方法与UnaryOperator相关的知识,希望对你有一定的参考价值。

  前提:本人在翻看《Java核心技术II》的时候在p17的时候发现一段代码不是很明白。不知道为什么就输出了1,2,3,4,5,6,7,8,9,10,...也不知道n-n.add(BigInteger.One)的功用是什么。

 


 代码如下:

Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n->n.add(BigInteger.ONE));
show("integers",integers);

 

  首先,BigInteger.ONE是表示BigInteger.ONE的常数。输出一下得到的是1。

System.out.println(BigInteger.ONE);

  遂去翻看Stream.iterate方法的实现。该方法的作用是

  • 返回有序无限连续Stream由函数的迭代应用产生f至初始元素seed ,产生Stream包括seedf(seed)f(f(seed)) ,等

    第一元件(位置0在) Stream将是提供seed 。 对于n > 0 ,位置n的元素将是将函数f应用于位置n - 1的元素的n - 1

    简单的说就是指定一个常量seed,产生从seed到常量f(由UnaryOperator返回的值得到)的流。这是一个迭代的过程。

public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
        ......

  return StreamSupport.stream(Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false); }

  发现iterate方法的第二个参数类型是UnaryOperator类型。找了一下UnaryOperator源代码。  UnaryOperator作用就是,返回且始终返回其输入参数的一元运算符。

public interface UnaryOperator<T> extends Function<T, T> {

    /**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

  所以n->n.add(BigInteger.ONE)的作用就是不断地生成比n大1的数,即代码同:

n = n.add(BigInteger.ONE);

  所以Stream.iterate(BigInteger.ONE, n->n.add(BigInteger.ONE));得到的是从1依次增1的BigInteger类型的流。

以上是关于Stream.iterate方法与UnaryOperator的主要内容,如果未能解决你的问题,请参考以下文章

,值得你一看

使用Stream输出斐波纳契元组序列

如何从无限流中创建Observable

Java8中重要的收集器Collector

Java生成8位数字按照从0开始到自己设置循环好多次

静态方法与实例方法,类方法与对象方法