6

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.

Dflip240
  • 115
  • 1
  • 7

2 Answers2

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 2
    If I did, you wouldn't have an infinite stream as you asked. you would just have a stream of 7 values. – JB Nizet Nov 27 '17 at 23:07
7

You might be thinking there's a way of using a map operation to generate the sequence. There isn't: Java non-terminal operations are, by design, only able to operate on one element at a time. This allows them to be converted to parallel streams with deterministic results.

Your best option is to generate an infinite stream. Here are a couple of ways of doing that:

class Fib {
    private int previous = 0;
    private int current = 1;

    private int next() {
        int temp = previous + current;
        previous = current;
        current = temp;
        return current;
    }

    public IntStream stream() {
        return IntStream.generate(this::next);
    }
}

used as new Fib().stream().

You can do this just using arrays as well:

IntStream fibStream = Stream.iterate(new int[]{0, 1}, a -> new int[]{a[1], a[0]+a[1]}).mapToInt(a -> a[1])
// print first 20 fibonacci number
fibStream.limit(20).forEach(System.out::println);
Ashutosh
  • 917
  • 10
  • 19
sprinter
  • 27,148
  • 6
  • 47
  • 78