Learnitweb

Generate Fibonacci Numbers Using Java Streams

Approach 1: Using Stream.iterate()

Generate the first n Fibonacci numbers:

int n = 10;

List<Integer> fibonacci = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
    .limit(n)
    .map(t -> t[0])
    .collect(Collectors.toList());

System.out.println(fibonacci);

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation:

  • Stream.iterate(new int[]{0,1}, t -> new int[]{t[1], t[0]+t[1]}) generates a stream of pairs [current, next].
  • .map(t -> t[0]) extracts the current Fibonacci number.
  • .limit(n) restricts the stream to the first n elements.
  • .collect(Collectors.toList()) converts it to a list.

This approach is functional, lazy, and efficient for generating Fibonacci numbers with Java Streams.