Skip to content

Instantly share code, notes, and snippets.

@artlovan
Created April 8, 2017 02:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save artlovan/d7315b375f4553a1be1605b16c7a9098 to your computer and use it in GitHub Desktop.
Save artlovan/d7315b375f4553a1be1605b16c7a9098 to your computer and use it in GitHub Desktop.
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<Integer> 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
Copy link

saborse commented Nov 25, 2017

Bravo! Good one!

@aarinsaras
Copy link

Class

@ShendeRahul
Copy link

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
Copy link

algdeff commented Jun 20, 2018

private Supplier<Stream> fibonacciBigDecStream() {
return () -> Stream.iterate(
new BigDecimal[] {BigDecimal.ZERO, BigDecimal.ONE},
p -> new BigDecimal[] {p[1], p[0].add(p[1])} )
.map(e -> e[0]);
}

@YorkShen
Copy link

Actually, due to the lack of standard pair in Java, this is the best we can do. And we could write more elegant code in Lisp with its built-in con-stream, which is the standard way of constructing a pair(i.e. stream)

(define (fibgen a b) (cons-stream a (fibgen b (+ a b)))) 
(define fibs (fibgen 0 1))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment