Instantly share code, notes, and snippets.

artlovan/Fibonacci.java Created Apr 8, 2017

Java 8 / Lambda approach to generate fibonacci series.
 import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Fibonacci { /** * Java 8 / Lambda approach to generate fibonacci series. * Fibonacci always start as classic (e.g. 0, 1, 1, 2, 3, 5) * @param series Number of how many fibonacci number should be generated * @return List holding resulting fibonacci number. */ public static List generate(int series) { return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) .limit(series) .map(n -> n[0]) .collect(toList()); } public static void main(String[] args) { System.out.println(Fibonacci.generate(10)); // Test the code. } }

saborse commented Nov 25, 2017

 Bravo! Good one!

 Class

ShendeRahul commented May 22, 2018

 Above code having compilation error @ Line No 17. Corrected the signature of generate(int series) as below : public static List generate(int series) { return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) .limit(series) .map(n -> n[0]) .collect(Collectors.toList()); }

algdeff commented Jun 20, 2018

 private Supplier fibonacciBigDecStream() { return () -> Stream.iterate( new BigDecimal[] {BigDecimal.ZERO, BigDecimal.ONE}, p -> new BigDecimal[] {p[1], p[0].add(p[1])} ) .map(e -> e[0]); }
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.