Is there a Java 8 stream operation that limits a (potentially infinite) Stream
until the first element fails to match a predicate?
In Java 9 we can use
I have another quick solution by implementing this (which is rly unclean in fact, but you get the idea):
public static void main(String[] args) {
System.out.println(StreamUtil.iterate(1, o -> o + 1).terminateOn(15)
.map(o -> o.toString()).collect(Collectors.joining(", ")));
}
static interface TerminatedStream {
Stream terminateOn(T e);
}
static class StreamUtil {
static TerminatedStream iterate(T seed, UnaryOperator op) {
return new TerminatedStream() {
public Stream terminateOn(T e) {
Builder builder = Stream. builder().add(seed);
T current = seed;
while (!current.equals(e)) {
current = op.apply(current);
builder.add(current);
}
return builder.build();
}
};
}
}