- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement the Fibonacci series using lambda expression in Java?
The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using "F(n)=F(n-1)+F(n-2)".
In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc.
Example
import java.util.List; import java.util.stream.*; public class FibonacciTest { public static void main(String args[]) { System.out.println(FibonacciTest.generate(10)); } public static List generate(int series) { return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression .limit(series) .map(n -> n[0]) .collect(Collectors.toList()); } }
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Advertisements