I was wondering when I created my own infinite stream with Stream.generate how the Streams which are in the standard library stop...
For example when yo
I have created a generic workaround for this
public class GuardedSpliterator implements Spliterator {
final Supplier extends T> generator;
final Predicate termination;
final boolean inclusive;
public GuardedSpliterator(Supplier extends T> generator, Predicate termination, boolean inclusive) {
this.generator = generator;
this.termination = termination;
this.inclusive = inclusive;
}
@Override
public boolean tryAdvance(Consumer super T> action) {
T next = generator.get();
boolean end = termination.test(next);
if (inclusive || !end) {
action.accept(next);
}
return !end;
}
@Override
public Spliterator trySplit() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long estimateSize() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int characteristics() {
return Spliterator.ORDERED;
}
}
Usage is pretty easy:
GuardedSpliterator source = new GuardedSpliterator<>(
() -> rnd.nextInt(),
(i) -> i > 10,
true
);
Stream ints = StreamSupport.stream(source, false);
ints.forEach(i -> System.out.println(i));