infinite streams
Brian Goetz
brian.goetz at oracle.com
Fri Mar 15 10:29:31 PDT 2013
Expanding...I'd meant you can use an Iterator as your generator and then
turn that into a stream:
Stream<T> s = Streams.stream(spliteratorUnknownSize(iterator, flags)))
Then you can still do streamy stuff with it. The suggestion of Iterator
was about where to put the state -- stateful lambdas as arguments to
methods like filter() will make your stream pipeline give wrong results
if someone every tries to use it in parallel.
On 3/15/2013 1:22 PM, Luc Duponcheel wrote:
> fair enough ...
>
> frankly I was hoping for Haskell and/or Scala functionality like takeWhile
>
> btw:
> thanks so much for the quick reply!
>
> Luc
>
>
>
> On Fri, Mar 15, 2013 at 5:54 PM, Brian Goetz <brian.goetz at oracle.com
> <mailto:brian.goetz at oracle.com>> wrote:
>
> 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
>
>
>
>
> --
> __~O
> -\ <,
> (*)/ (*)
>
> reality goes far beyond imagination
More information about the lambda-dev
mailing list