How to implement the Fibonacci series using lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using "F(n)=F(n-1)+F(n-2)".

In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc.

Example

import java.util.List;
import java.util.stream.*;

public class FibonacciTest {
   public static void main(String args[]) {
      System.out.println(FibonacciTest.generate(10));
   }
   public static List generate(int series) {
      return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression
                  .limit(series)
     .map(n -> n[0])
     .collect(Collectors.toList());
   }
}

Output

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
raja
Published on 08-Jan-2020 06:29:41
Advertisements