In the previous post, I showed a Fibonacci series Java program using for loop and Fibonacci Series Java Program Using Recursion.
In this Java program, I show you how to calculate the Fibonacci series of a given number using Java 8 streams.
Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
```
In this Java program, I show you how to calculate the Fibonacci series of a given number using Java 8 streams.
Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
```
Fibonacci Series Java Program Using Stream API
package net.javaguides.corejava.programs; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream; public class FibonacciStreamProgram { public static List < Integer > fibonacci(int limit) { return Stream.iterate(new int[] { 0, 1 }, t - > new int[] { t[1], t[0] + t[1] }) .limit(limit) .map(n - > n[0]) .collect(Collectors.toList()); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); System.out.println(fibonacci(n) + "\t"); scanner.close(); } }
Output
Enter a number: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Related Java Programs
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course