I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc.
H
You can use a variable in your lambda expression to temporarily store the previous element, which is needed to calculate the next element in the fibonacci sequence.
public class FibonacciGenerator {
private long prev=0;
public void printSequence(int elements) {
LongStream.iterate(1, n -> {n+=prev; prev=n-prev; return n;}).
limit(elements).forEach(System.out::println);
}
}
Normally the method and the field would rather be declared as static but I wanted to show that instance fields can be used as well.
Please note that you could not use a local variable ( declared in a method or passed to a method ) instead of a field, for such variables need to be final in order to use them in lambdas. For our purpose we needed a mutable variable to store the different values during the iteration.