1

I'm trying to create a fibonacci sequence through the usage of Java Streams API. I've create a supplier, but I want it to stop at a specific value (e.g 1000000).

The suplier:

import java.util.function.Supplier;

public class FibonacciSupplier implements Supplier<Integer> {

    private int current;
    private int next;

    public FibonacciSupplier() {
        current = 0;
        next = 1;
    }

    @Override
    public Integer get() {
        int result = current;
        current = next + current;
        next = result;
        return result;
    }
}

How I would like it to be:

Stream.generate(new FibonacciSupplier()).maxValue(1000000);

The maxValue does not exist as a function, I'm using it as a name to for context.

Niku Hysa
  • 66
  • 1
  • 12

2 Answers2

3

The best solution is to use takeWhile, which is available in Java 9+:

Stream.generate(new FibonacciSupplier())
    .takeWhile(i -> i <= 1000000) //will stop stream when value exceeds given limit
    .forEach(System.out::println);

If you're using Java 8, then you may want to look into hacks for stopping an infinite stream

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

You'll need to use the .limit() method on the stream as below :

Stream.generate(new FibonacciSupplier()).limit(1000).forEach(System.out::println);

From the docs,

Returns a stream consisting of the elements of this stream, truncated to be no longer than {@code maxSize} in length.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • `takeWhile` from java9 will do the job – kofemann Nov 07 '18 at 17:46
  • 1
    Eh... Yes and no. limit limits by the number of elements. He wants to stop once the sequence has exceeded a certain value. How do you know that a fib number of 1000000 is element 1000? – Michael Nov 07 '18 at 17:48