问题描述
我为Java8 迭代器的自然数的无限序列(
。 Stream
)定义了自然
I defined natural
for Infinite sequence (Stream
) of Natural numbers with Java8 iterator
.
IntStream natural = IntStream.iterate(0, i -> i + 1);
natural
.limit(10)
.forEach(System.out::println);
现在,我想用Java8 generator $ c $定义它c>。
Now, I want to define it with Java8 generator
.
静态流生成(供应商)
最简单的方法是什么?谢谢。
What would be the simplest way? Thanks.
推荐答案
注意:@assylias使用 AtomicInteger设法用lambda做到了/ code>。
他应该有接受的答案。
Note: @assylias managed to do it with a lambda using AtomicInteger
. He should probably have the accepted answer.
我不确定你可以使用lambda(因为它是有状态的),但是使用普通的供应商
这可以工作:
I'm not sure you can do that with a lambda (because it is stateful), but with a plain Supplier
this would work:
IntSupplier generator = new IntSupplier() {
int current = 0;
public int getAsInt() {
return current++;
}
};
IntStream natural = IntStream.generate(generator);
然而,我非常喜欢您当前的解决方案,因为这是目的of iterate(int seed,IntUnaryOperator f)
恕我直言:
However, I highly prefer your current solution, because this is the purpose of iterate(int seed, IntUnaryOperator f)
IMHO:
IntStream natural = IntStream.iterate(0, i -> i + 1);
这篇关于Java8生成器的自然数无限序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!