Search code examples
javaintfibonacci

Using Intstream to generate infinite Fibonacci sequence


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.


Solution

  • 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.