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
import java.util.stream.Stream;
: This line imports theStream
class, a central component of the Java Stream API.public class FibonacciSeries { ... }
: This defines a public class namedFibonacciSeries
, which encapsulates themain
method.public static void main(String[] str){ ... }
: This is the entry point of the Java program.Stream.iterate(new int[]{0,1}, f->new int[]{f[1],f[0]+f[1]})
: This line initiates the generation of the Fibonacci sequence usingStream.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 anint[]
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.
- The first element (
.limit(10)
: This intermediate operation limits the stream to the first 10 elements generated by theiterate()
method..map(f->f[0])
: This intermediate operation transforms each element of the stream. Sinceiterate()
generates arrays ofint[]
, thismap
operation extracts the first element (f[0]
) from each array, which corresponds to the Fibonacci number displayed..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