Java 8 Lambda expressions for solving fibonacci (non recursive way)

后端 未结 6 1155
广开言路
广开言路 2020-12-03 07:27

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 07:42

    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.

提交回复
热议问题