In this tutorial, we will see “How to find or print the Fibonacci Series using Java 8 Streams API?”
Find or Print Fibonacci Series using Java 8 Streams API
Java 8 – Print Fibonacci Series for a given number using Streams? (Simplest Example) Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /** * Using Java 8, Print Fibonacci Series * @author Deepak Verma * */ import java.util.stream.Stream; public class Print_Fibonacci_Series_Java8_Example { public static void main(String[] args) { int number = 10; Stream.iterate(new int[]{0, 1}, x -> new int[]{x[1], x[0] + x[1]}) .limit(number) .map(y -> y[0]) .forEach(System.out::println); } } |
Output:
1 2 3 4 5 6 7 8 9 10 | 0 1 1 2 3 5 8 13 21 34 |
Find or Print Fibonacci Series using Java 8 Streams API
In the above example, It uses iterate
method of Streams to generate an infinite stream of integer
arrays, where each array contains the next two terms in the sequence. After that, The limit
method is applied to limit the stream to the first number
terms, and then map
method is applied to extract the first term of each array, which actually represents the next number in the Fibonacci series. And, at last, forEach
method is used to print each number to the console by applying sysout.
Find or Print Fibonacci Series using Java 8 Streams API
Java 8 – Print Fibonacci Series for a given number using Streams? (Simplest Example) Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: