/home/wpollock1/public_html/AJava/FibonacciStream.java
// Demo of Java 8 Stream and generators. In this class, fibStream returns
// a Stream of Longs where each element is a Fibonacci number. This
// is an infinite sequence, so we limit the number of elements.
//
// Written 11/2016 by Wayne Pollock, Tampa Florida USA, based on code from
// Wikipedia <en.wikipedia.org/wiki/Generator_%28computer_programming%29#Java>
import java.util.function.*;
import java.util.stream.*;
public class FibonacciStream {
public static void main ( String[] args ) {
int num = 0;
try {
num = Integer.parseInt( args[0] );
if ( num < 0 )
throw new IllegalArgumentException( "Must be a positive Integer" );
} catch ( Exception e ) {
System.err.println( "Usage: java FibonacciStream <num>\n"
+ "\twhere <num> is a positive Integer" );
System.exit( 1 );
}
System.out.println("Fibonacci numbers: fib(0) through fib(" + num + "):" );
// Print the first num-th Fibonacci numbers:
// (Note, the "+1" is because most people forget that the first one is
// fib(0); when someone says they want the 10th Fibonacci number, they
// usually mean fib(10), but that is the 11-th Fibonacci number!)
fibStream(num+1).forEach( System.out::println );
}
/**
* Generate a Stream of Fibonacci numbers.
* @param num the length of the sequence desired.
* @return Stream<Long of the given length, of Fibonacci numbers.
*/
private static Stream<Long> fibStream ( int num ) {
// Pass an anonymous local class to Stream.generate:
Stream<Long> myStream = Stream.generate( new Supplier<Long>() {
long previous = 0, next = 1;
public Long get () {
long current = previous;
previous = next;
next = previous + current;
return current;
}
});
return myStream.limit( num );
}
}
/*
public Iterable<Long> fibonacci(int limit){
return ()->{
return Stream.generate(new Supplier<Long>() {
long previous = 0, next = 1;
public Long get() {
long current = previous;
previous = next;
next = previous + current;
return current;
}
}).limit(limit).iterator();
}
}
// this could then be used as...
for (int f: fibonacci(10)) {
System.out.println(f);
}
*/