How to Generate Fibonacci Numbers in Java


In this example, we will demonstrate how to use Stream to generate Fibonacci numbers in Java.

Source Code

package com.beginner.examples;

import java.util.stream.Stream;

public class FibonacciExample {

    public static void main(String[] args){
    	//ruse Stream.iterate().
    	Stream.iterate(new int[]{0, 1}, i -> new int[]{i[1], i[0] + i[1]})
		.limit(6).forEach(x -> System.out.println(x[0]));
    }
}

Output:

0
1
1
2
3
5

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments