# FibonacciStream.java

``` 1: // Demo of Java 8 Stream and generators.  In this class, fibStream returns
2: // a Stream of Longs where each element is a Fibonacci number.  This
3: // is an infinite sequence, so we limit the number of elements.
4: //
5: // Written 11/2016 by Wayne Pollock, Tampa Florida USA, based on code from
6: // Wikipedia <en.wikipedia.org/wiki/Generator_%28computer_programming%29#Java>
7:
8: import java.util.function.*;
9: import java.util.stream.*;
10:
11: public class FibonacciStream {
12:    public static void main ( String[] args ) {
13:       int num = 0;
14:       try {
15:          num = Integer.parseInt( args );
16:          if ( num < 0 )
17:             throw new IllegalArgumentException( "Must be a positive Integer" );
18:       } catch ( Exception e ) {
19:          System.err.println( "Usage: java FibonacciStream <num>\n"
20:             + "\twhere <num> is a positive Integer" );
21:          System.exit( 1 );
22:       }
23:
24:       System.out.println("Fibonacci numbers: fib(0) through fib(" + num + "):" );
25:       // Print the first num-th Fibonacci numbers:
26:       // (Note, the "+1" is because most people forget that the first one is
27:       // fib(0); when someone says they want the 10th Fibonacci number, they
28:       // usually mean fib(10), but that is the 11-th Fibonacci number!)
29:       fibStream(num+1).forEach( System.out::println );
30:    }
31:
32:    /**
33:     * Generate a Stream of Fibonacci numbers.
34:     * @param num the length of the sequence desired.
35:     * @return Stream<Long of the given length, of Fibonacci numbers.
36:    */
37:    private static Stream<Long> fibStream ( int num ) {
38:       // Pass an anonymous local class to Stream.generate:
39:       Stream<Long> myStream = Stream.generate( new Supplier<Long>() {
40:           long previous = 0, next = 1;
41:
42:           public Long get () {
43:               long current = previous;
44:               previous = next;
45:               next = previous + current;
46:               return current;
47:           }
48:       });
49:       return myStream.limit( num );
50:    }
51: }
52:
53: /*
54: public Iterable<Long> fibonacci(int limit){
55:     return ()->{
56:         return Stream.generate(new Supplier<Long>() {
57:             long previous = 0, next = 1;
58:
59:             public Long get() {
60:                 long current = previous;
61:                 previous = next;
62:                 next = previous + current;
63:                 return current;
64:             }
65:         }).limit(limit).iterator();
66:     }
67: }
68:
69: // this could then be used as...
70: for (int f: fibonacci(10)) {
71:     System.out.println(f);
72: }
73:
74: */
```