Java8生成器的无限序列自然数

19 java iterator generator java-8

我用Java8 定义naturalStream自然数的无限序列()iterator.

IntStream natural = IntStream.iterate(0, i -> i + 1);

natural
 .limit(10)
 .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

现在,我想用Java8定义它generator.

静态流生成(供应商)

什么是最简单的方法?谢谢.

ass*_*ias 24

With a generator you need to keep track of your current index. One way would be:

IntStream natural = IntStream.generate(new AtomicInteger()::getAndIncrement);
Run Code Online (Sandbox Code Playgroud)

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.


Dav*_*ips 19

这内置于IntStream:

IntStream.range(0, Integer.MAX_VALUE)
Run Code Online (Sandbox Code Playgroud)

这将返回所有值(但不包括)Integer.MAX_VALUE.


Jof*_*rey 12

Note: @assylias managed to do it with a lambda using AtomicInteger. He should probably have the accepted answer.


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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)