Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 725
Dflip240 Avatar asked Nov 27 '17 22:11

Dflip240


2 Answers

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.

like image 192
JB Nizet Avatar answered Oct 01 '22 16:10

JB Nizet


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);
like image 22
sprinter Avatar answered Oct 01 '22 16:10

sprinter