2

Is there a way I can terminate a Stream (apart from .limit(long)).

What I'm really looking for is a kind of .until(Predicate<T>). Method filter is obviously not usable here.

Example:

Stream.iterate(service.first(), service::next)
  .until(item -> item.isTerminator())

This example might not make sense, but shows the concept I'm looking for.

Is it even possible to do something like that?

vuk
  • 501
  • 1
  • 5
  • 9
  • 1
    [Seems not](http://stackoverflow.com/questions/20746429/java-8-limit-infinite-stream-by-a-predicate), however interesting. – user2504380 Oct 08 '14 at 09:57
  • U can use this ( and make it a little more clean) : 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(); } }; } } – user2504380 Oct 08 '14 at 10:50
  • With some changes, this works with predicate. However it stores up the values in "terminateOn" which ruins the whole concept of using Streams :) – vuk Oct 08 '14 at 11:46
  • in how far? you dont mix up streams with io.streams do you? a stream is, as far as i know, a pipe-like representation of a collection, so it has a fixed size anyway and does not react to additional input in any way. An "infinite" stream is also not a mutable object supplied by constant input but one object that is finished after infinite recursion (never, if you dont set a limit). Please correct or tell me what meant with "ruins", I dont have a lot of knowledge here to be honest. – user2504380 Oct 08 '14 at 12:24
  • No Streams are not simply a representation of an old style collection. See Stream.iterate(), which is an infinite stream of objects. You can convert into a collection using a collector at the end, that's true, but in between it will never be a collection. Your code is nice, but builds up a static, in-memory collection of elements as a stream, does not delegate fetching to the upstream (as limit(long) method does). – vuk Oct 08 '14 at 14:09

0 Answers0