It would be great to have an additional factory method
interface Iterator<T> {
static <T> Iterator<T> iterate(Supplier<Boolean> hasNext, Supplier<? extends T> next) {
return new AbstractIterator<>() {
@Override
public boolean hasNext() {
return hasNext.get();
}
@Override
public T getNext() {
return next.get();
}
};
}
}
It makes sense to also add this method to Stream:
interface Stream<T> {
static <T> Stream<T> iterate(Supplier<Boolean> hasNext, Supplier<? extends T> next) {
return Stream.ofAll(Iterator.iterate(hasNext, next));
}
}
Hint: The addition might introduce ambiguities regarding existing iterate() methods.
Another factory method worth considering could be one accepting a Supplier<Option<? extends T>>,
which would repeatedly invoke the supplier while it's a Some and end on the first None.
I like @nfekete idea because it allows the data and the predicate to be tied together.
what about
interface Iterator<T> {
static <T> Iterator<T> iterate(Supplier<? extends T> next, Predicate<? extends T> until);
}
so you can do Iterator.iterate(StringUtils::randomString,s -> s.length() > 10)
@chb0github your Iterator#iterate(Supplier<T>, Predicate<T>) can be replaced with exists Iterator.continually(Supplier<T>).takeUntil(Predicate<T>): Iterator.continually(StringUtils::randomString).takeUntil(s -> s.length() > 10)
Variant iterate(Supplier<Option<? extends T>>) is more suitable as I think.
This situation looks like the https://github.com/vavr-io/vavr/issues/2134#issuecomment-342297157
iterate(Supplier<Boolean> hasNext, Supplier<? extends T> next) requires synchronized common state of both suppliers. In fact, one should implement Supplier<Option> factory and pass it to Iterator.iterate(Supplier, Supplier). I believe Iterator.iterate(Supplier<Option>) is enough.
I believe Iterator.iterate(Supplier
Yes, I also think @ruslansennov is right. Will close this ticket.
Solved with #2193
Most helpful comment
Another factory method worth considering could be one accepting a
Supplier<Option<? extends T>>,which would repeatedly invoke the supplier while it's a
Someand end on the firstNone.