Created
April 8, 2017 02:10
-
-
Save artlovan/d7315b375f4553a1be1605b16c7a9098 to your computer and use it in GitHub Desktop.
Java 8 / Lambda approach to generate fibonacci series.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
} | |
} |
Class
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());
}
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]);
}
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
Bravo! Good one!