java 使用 Java8 生成器生成无限自然数序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26277330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Infinite sequence of Natural numbers with Java8 generator
提问by David Phillips
I defined natural
for Infinite sequence (Stream
) of Natural numbers with Java8 iterator
.
我用 Java8定义natural
了Stream
自然数的无限序列 ( ) iterator
。
IntStream natural = IntStream.iterate(0, i -> i + 1);
natural
.limit(10)
.forEach(System.out::println);
Now, I want to define it with Java8 generator
.
现在,我想用 Java8 定义它generator
。
static Stream generate(Supplier s)
静态流生成(供应商)
What would be the simplest way? Thanks.
什么是最简单的方法?谢谢。
采纳答案by Joffrey
Note: @assylias managed to do it with a lambda using AtomicInteger
.He should probably have the accepted answer.
注意:@assylias 使用AtomicInteger
. 他可能应该得到公认的答案。
I'm not sure you can do that with a lambda (because it is stateful), but with a plain Supplier
this would work:
我不确定你可以用 lambda 来做到这一点(因为它是有状态的),但如果是简单的,Supplier
这会起作用:
IntSupplier generator = new IntSupplier() {
int current = 0;
public int getAsInt() {
return current++;
}
};
IntStream natural = IntStream.generate(generator);
However, I highly prefer your current solution, because this is the purpose of iterate(int seed, IntUnaryOperator f)
IMHO:
但是,我非常喜欢您当前的解决方案,因为这是iterate(int seed, IntUnaryOperator f)
恕我直言的目的:
IntStream natural = IntStream.iterate(0, i -> i + 1);
回答by assylias
With a generator you need to keep track of your current index. One way would be:
使用生成器,您需要跟踪当前索引。一种方法是:
IntStream natural = IntStream.generate(new AtomicInteger()::getAndIncrement);
Note: I use AtomicInteger as a mutable integer rather than for its thread safety: if you parallelise the stream the order will not be as expected.
注意:我使用 AtomicInteger 作为可变整数而不是为了它的线程安全:如果你并行化流,顺序将不会像预期的那样。
回答by David Phillips
This is built into IntStream
:
这内置于IntStream
:
IntStream.range(0, Integer.MAX_VALUE)
This returns all values up to (but not including) Integer.MAX_VALUE
.
这将返回所有值(但不包括)Integer.MAX_VALUE
。