R4R Style Learning Portal

Fibonacci series using java 8 stream API

The Java code provided uses the Stream.iterate() method to generate the Fibonacci series, which is a sequence of numbers where each number is the sum of the two preceding ones. The sequence typically starts with 0 and 1: 0, 1, 1, 2, 3, 5, 8, and so on. 
Here's a breakdown of the code:
import java.util.stream.Stream; // Import the Stream class

public class FibonacciSeries {
    public static void main(String[] str){
        Stream.iterate(new int[]{0,1}, f->new int[]{f[1],f[0]+f[1]}) // Initialize the stream with a seed and a function
                .limit(10) // Limit the stream to the first 10 Fibonacci numbers
                .map(f->f[0]) // Extract the first element from each array (which is the Fibonacci number)
                .forEach(i->System.out.println(i+" ")); // Print each Fibonacci number
    }
}
Explanation
  1. import java.util.stream.Stream;: This line imports the Stream class, a central component of the Java Stream API.
  2. public class FibonacciSeries { ... }: This defines a public class named FibonacciSeries, which encapsulates the main method.
  3. public static void main(String[] str){ ... }: This is the entry point of the Java program.
  4. Stream.iterate(new int[]{0,1}, f->new int[]{f[1],f[0]+f[1]}): This line initiates the generation of the Fibonacci sequence using Stream.iterate().
    • new int[]{0,1}: This is the initial seed value of the stream, an array of two integers representing the first two Fibonacci numbers (F0 and F1).
    • f->new int[]{f[1],f[0]+f[1]}: This lambda expression serves as the unary operator. It takes the previous element (f, which is an int[]array) and generates the next element. It creates a new array where:
      • The first element (f[1]) becomes the current Fibonacci number.
      • The second element (f[0]+f[1]) becomes the next Fibonacci number in the sequence.
  5. .limit(10): This intermediate operation limits the stream to the first 10 elements generated by the iterate() method.
  6. .map(f->f[0]): This intermediate operation transforms each element of the stream. Since iterate() generates arrays of int[], this map operation extracts the first element (f[0]) from each array, which corresponds to the Fibonacci number displayed.
  7. .forEach(i->System.out.println(i+" ")): This is a terminal operation that consumes each element of the stream. It takes each extracted Fibonacci number (i) and prints it to the console, followed by a space.
 
Output

0 1 1 2 3 5 8 13 21 34