🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In this guide, we'll explore how to generate the Fibonacci series in Java using the Stream API, which was introduced in Java 8.
Problem Statement
Create a Java program that:
- Generates a specified number of Fibonacci numbers.
- Uses the Java 8 Stream API to generate the series.
Example 1:
- Input:
10(first 10 Fibonacci numbers) - Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Example 2:
- Input:
5(first 5 Fibonacci numbers) - Output:
0, 1, 1, 2, 3
Solution Steps
- Create a Stream to Generate Fibonacci Numbers: Use the
Stream.iteratemethod to generate a stream of Fibonacci numbers. - Limit the Number of Fibonacci Numbers: Use the
limitmethod to restrict the stream to the desired number of elements. - Collect and Print the Series: Collect the Fibonacci numbers into a list and print them.
Java Program
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java Program to Generate Fibonacci Series using Stream API
* Author: https://www.javaguides.net/
*/
public class FibonacciStream {
public static void main(String[] args) {
// Step 1: Define the number of Fibonacci numbers to generate
int n = 10; // You can change this to generate more or fewer numbers
// Step 2: Generate the Fibonacci series using Stream API
List<Integer> fibonacciSeries = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
.limit(n)
.map(t -> t[0])
.collect(Collectors.toList());
// Step 3: Output the Fibonacci series
System.out.println("First " + n + " Fibonacci numbers: " + fibonacciSeries);
}
}
Explanation
Step 1: Define the Number of Fibonacci Numbers to Generate
- The variable
nis set to determine how many Fibonacci numbers you want to generate. For this example, it's set to10.
Step 2: Generate the Fibonacci Series Using Stream API
- Stream.iterate: This method creates an infinite stream of Fibonacci pairs. The seed is the initial pair
[0, 1], and the function passed toiterategenerates the next pair by summing the previous two numbers.t -> new int[]{t[1], t[0] + t[1]}: This lambda expression produces the next pair in the Fibonacci sequence.
- limit(n): Limits the stream to the first
nelements. - map(t -> t[0]): Extracts the first element of each pair (which is the actual Fibonacci number).
- collect(Collectors.toList()): Collects the generated Fibonacci numbers into a list.
Step 3: Output the Fibonacci Series
- The program prints the list of Fibonacci numbers.
Output Examples
Example 1:
First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Example 2:
First 5 Fibonacci numbers: [0, 1, 1, 2, 3]
Conclusion
This Java program demonstrates how to generate the Fibonacci series using the Stream API. By leveraging the power of Stream.iterate, the program creates an infinite stream of Fibonacci numbers, which can be limited and collected as needed. This method is not only concise but also highly readable, making it an excellent choice for generating sequences like the Fibonacci series in Java.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment