Search code examples
java-8java-streamshort-circuiting

How to test if it is a Fibonacci Stream?


This is not a fibonacci stream.

LongStream digits = LongStream.of(0, 1, 2 , 3 , 4, 5, 6, 7, 8, 9);

Neither is this.

LongStream naturals = LongStream.iterate(1,  (i) -> i + 1);

But, how do you check that they are not?

Notice that the second stream is infinite, so you need some short-circuit operation to stop as soon as possible. Unfortunately, the short-circuit methods 'allMatch' and 'anyMatch' only tests on elements, not the sequence.


Solution

  • Using Guava Iterables.elementsEqual:

    Supplier<Integer> fibonacci = new Supplier<Integer>() {
            int first = 0;
            int second = 1;
    
            @Override
            public Integer get() {
                int result = first + second;
                first = second;
                second = result;
                return first;
            }
        };
    boolean isMatch = Iterables.elementsEqual(
                         toTest, 
                         Stream.generate(fibonacci).limit(toTest.size()).collect(Collectors.toList()));