Skip to content

Instantly share code, notes, and snippets.

@artlovan
Created April 8, 2017 02:10
Show Gist options
  • 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.
}
}
@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