1

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.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • 1
    I don't see how you could test that an infinite stream is a fibonacci stream. Even if you test the first 1,000,000 elements follow the fibonacci sequence, nothing guarantees that the 1,000,001th one will. – JB Nizet Mar 29 '15 at 15:08
  • 1
    If a `zip` method was provided you could something like `boolean same = zip(fib.boxed(), naturals.boxed(), (a, b) -> a.equals(b)).allMatch(x -> x == true);` (note that `(a, b) -> a.equals(b)` could be reduced to `Objects::equals`). You can check this thread: http://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip But yes for infinite streams you can `limit` the stream before but it's not because n-1 elements are equals that the nth one will be... – Alexis C. Mar 29 '15 at 15:10
  • Forget about infinite stream if it is a problem. I said it only to force a short-circuit operation on your answers :P . In fact, I dont mind about Fibonacci. I could ask the next question instead: "How do you test that a stream is ordered without the need to iterate all its elements?" –  Mar 29 '15 at 19:22
  • 1
    Well it depends. You can try to grab the Stream's spliterator and see if it has the SORTED characteristic. Otherwise I'm afraid the only way is to iterate through all the elements. As of any sequence, you can't know it its sorted until you have compared all the elements in the order you encounter them. – Alexis C. Mar 29 '15 at 19:51
  • @atalarico Given the advice you've received regarding infinite streams and determining order etc., what is your question now? – Duncan Jones Mar 30 '15 at 09:25

1 Answers1

1

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()));
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130