Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

saborse commented Nov 25, 2017

Bravo! Good one!

@aarinsaras

This comment has been minimized.

aarinsaras commented Feb 19, 2018

Class

@ShendeRahul

This comment has been minimized.

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

This comment has been minimized.

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]);
}

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