Add Streams.iterate(T seed, UnaryOperator<T> f, Predicate<T> stop)
See original GitHub issueStream has a two argument version of iterate
that takes a seed (T seed
) and an iterative function (UnaryOperator<T> f
) and generates an infinite stream by repeatedly applying the function. This is an almost perfect replacement for a traditional for loop, except that it’s missing a termination predicate. Java 9 adds takeWhile
which can be used to terminate a stream generated this way, but unfortunately some of us aren’t beyond Java 8 yet.
It might be nice to add a static method <T> Stream<T> iterate(T seed, UnaryOperator<T> f, Predicate<T> stop)
to the Streams
utility class that could fill this niche, at least until Java 11 is out and widely considered stable. An alternative (or possibly additional) approach would be adding a static takeWhile
method to the same class that would limit the Stream by some predicate, though that’s a bit clunkier.
Thanks, and let me know if you need more details or any clarification.
Issue Analytics
- State:
- Created 5 years ago
- Comments:6
Top GitHub Comments
Well. That’s just my personal observation as I don’t run into needing this often.
Let’s see what the Guava maintainers think. 😃
Speculating about the API, I think the
iterate(initial, step, stop)
signature as is may not be self-evident enough. It’s equally likely to think of the predicate aswhile
instead ofuntil
because it’s what a for-loop will look like.And I suppose adding two similar APIs like
iterateUntil
anditerateWhile
might be too much for little gain.On the other hand, the more generic
generate(initial, iterate)
signature could be used to create a less ambiguous syntax, but you’ll need to add two helpersstreamWhile()
andstreamUntil()
in the local code base.Then: