I am writing a code to calculate Fibonacci numbers. With this code I can generate first n numbers of the Fibonacci sequence.
Stream.generate(new Supplier<Long>() {
private long n1 = 1;
private long n2 = 2;
@Override
public Long get() {
long fibonacci = n1;
long n3 = n2 + n1;
n1 = n2;
n2 = n3;
return fibonacci;
}
}).limit(50).forEach(System.out::println);
The method limit
returns the Stream
which holds the number of elements passed to this method. I want to stop the generation of the Stream
after the Fibonacci number reached some value.
I mean if I want to list all Fibonacci numbers less than 1000 then I cannot use limit
, because I don't know how many Fibonacci numbers there could be.
Is there any way to do this using lambda expressions?