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.


import java.util.List;

public class FibonacciTest {
   public static void main(String args[]) {
   public static List generate(int series) {
      return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression
     .map(n -> n[0])


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Updated on 13-Jul-2020 09:24:29