[英]java 8 make a stream of the multiples of two
I'm practicing streams in java 8 and im trying to make a Stream<Integer>
containing the multiples of 2. There are several tasks in one main class so I won't link the whole block but what i got so far is this: 我在java 8中练习流,我试图创建一个包含2的倍数的Stream<Integer>
。在一个主类中有几个任务所以我不会链接整个块但是到目前为止我得到的是:
Integer twoToTheZeroth = 1;
UnaryOperator<Integer> doubler = (Integer x) -> 2 * x;
Stream<Integer> result = ?;
My question here probably isn't related strongly to the streams, more like the syntax, that how should I use the doubler to get the result? 我的问题可能与流不相关,更像是语法,我应该如何使用doubler来获得结果?
Thanks in advance! 提前致谢!
You can use Stream.iterate
. 您可以使用Stream.iterate
。
Stream<Integer> result = Stream.iterate(twoToTheZeroth, doubler);
or using the lambda directly 或直接使用lambda
Stream.iterate(1, x -> 2*x);
The first argument is the "seed" (ie first element of the stream), the operator gets applied consecutively with every element access. 第一个参数是“种子”(即流的第一个元素),运算符连续应用于每个元素访问。
EDIT: 编辑:
As Vinay points out, this will result in the stream being filled with 0s eventually (this is due to int overflow). 正如Vinay指出的那样,这将导致流最终被填充为0(这是由于int溢出)。 To prevent that, maybe use BigInteger
: 为了防止这种情况,可以使用BigInteger
:
Stream.iterate(BigInteger.ONE,
x -> x.multiply(BigInteger.valueOf(2)))
.forEach(System.out::println);
Arrays.asList(1,2,3,4,5).stream().map(x -> x * x).forEach(x -> System.out.println(x));
所以你可以在map
来电者中使用doubler
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.