infinite streams
Brian Goetz
brian.goetz at oracle.com
Fri Mar 15 09:54:11 PDT 2013
In cases like this, you probably want to use an Iterator instead.
Iterators are expected to be stateful in this way.
On 3/15/2013 12:40 PM, Luc Duponcheel wrote:
> 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
>
More information about the lambda-dev
mailing list