firstly, thanks for the comments by @Olivier Grégoire. he changes his response to new knowledge.
write your own Spliteratorfor an unknown size nextInts, then you can use StreamSupport#streamto create a stream for nextInts. eg:
generateUntil(this::nextInts, List::isEmpty).forEach(list -> {
});
import static java.util.stream.StreamSupport.stream;
<T> Stream<T> generateUntil(final Supplier<T> generator, Predicate<T> stop) {
long unknownSize = Long.MAX_VALUE;
return stream(new AbstractSpliterator<T>(unknownSize, Spliterator.ORDERED) {
@Override
public boolean tryAdvance(Consumer<? super T> action) {
T value = generator.get();
if (stop.test(value)) {
return false;
}
action.accept(value);
return true;
}
}, false);
}
source
share