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.

2
  • Have you tried using an if statement? if (value > 1000000) { dontDo(); }? Commented Nov 7, 2018 at 17:29
  • 1
    limit might be what you need. Is that what you need? Commented Nov 7, 2018 at 17:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

If you knew that question existed, why didn't you close this as a dupe?
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.

2 Comments

takeWhile from java9 will do the job
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.