infinite streams

Luc Duponcheel luc.duponcheel at gmail.com
Fri Mar 15 09:40:38 PDT 2013


Hello all,

just by looking at the API's I came up with the
following program (see below) for generating/printing
fibonacci numbers [ agreed: not very original :-) ]

the code works fine, but, my question is:
the BooleanSupplier cannot make use of the current
fibonacci number (e.g. I want to stop printing when
the fibonacci number is greater than, say, 1000)

ps:

my code is not the most "functional" one can think of
[ it uses two mutable variables (i and j) ]

any alternative approaches?

thx

=== begin code ===

package whatever

import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.Streams;

public class FibApp {

 public static void main(String[] args) {
  Stream<Integer> fibs =
          Streams.generate(
          new Supplier<Integer>() {
   private int i = 1;
   private int j = 1;

   @Override
   public Integer get() {
    Integer result = new Integer(i);
    int tmp = i;
    i = j;
    j = j + tmp;
    return result;
   }
  });
  fibs.forEachUntil(n -> {
   System.out.print(n + " ");
  }, () -> Math.random() < 0.1);
  System.out.println();
 }
}

=== end code ===

Luc

-- 
   __~O
  -\ <,
(*)/ (*)

reality goes far beyond imagination


More information about the lambda-dev mailing list