标签:streams function 元素 output int put operator inter type
前提:本人在翻看《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包括seed , f(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
标签:streams function 元素 output int put operator inter type
原文地址:https://www.cnblogs.com/NYfor2018/p/9009468.html