This is the fourth solution to find the nTh number of the Fibonacci series. The logic uses the Stream API of java.
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class nthFibUsingStreamAPI {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
// To find the nTh number of Fibonacci series, read nTh value here.
System.out.print("Enter nTh number=");
int nTh = number.nextInt();
number.close();
List<Integer> fibSeries = Stream.iterate(new int[] { 0, 1 }, t -> new int[] { t[1], t[0] + t[1] }).limit(nTh)
.map(k -> k[0]).collect(Collectors.toList());
System.out.println((fibSeries.get(nTh - 1)));
}
}
OUTPUT:
Enter nTh number=
16
The 16th value of the Fibonacci series is 610

Leave a comment