Using Intstream to generate infinite Fibonacci sequence

Dflip240 :

Im having a little issue figuring out how to use stream to generate an infinite sized, sequential stream which contains all the numbers in a fibonacci sequence.

How would I be able to print out an infinite stream? Any advice helps, thanks.

JB Nizet :
public class Fibonacci {

    public static void main(String[] args) {
        IntStream stream = IntStream.generate(new FibonacciSupplier());
        stream.limit(20).forEach(System.out::println);
    }

    private static class FibonacciSupplier implements IntSupplier {

        int current = 1;
        int previous = 0;

        @Override
        public int getAsInt() {
            int result = current;
            current = previous + current;
            previous = result;
            return result;
        }
    }
}

Note however that this stream can't be infinite as soon as you reach the 47th element, the value is too large to fit into a positive integer.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475897&siteId=1