Ken OKABE Ken OKABE - 10 hours ago 2
Java Question

Infinite sequence of Natural numbers with Java8 generator

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);


Now, I want to define it with Java8
generator
.

static Stream generate(Supplier s)

What would be the simplest way? Thanks.

Answer

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);

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);