Skip to Main Content

How to stop an infinite Stream?

Markus KARGMay 26 2014 — edited Jun 6 2014

I have a Stream instace which produces values using an infinite Supplier (it supplies values taken from an electronic sensor -- so unless the battery is low, the sensor will provide "for ever").

The stream is processed by a Collector using Stream.collect() (e. g. imagine that the values from the sensor should be averaged; in fact what it does is a bit more compliacted maths).

The problem is that the collector does not produce a result but hangs up, as the supplier does never stop providing more sensor values.

So what I need is a limitation rule that stops the stream. While there is a Stream.limit(long) method, it actually does not solve my problem as in my case it is not practical to stop after a particular count, while I actually want to stop streaming when the sensor value exceeds a particular limit etc. (hence, voids an arbitrary rule).

To sum up, what I need is Stream.limit(Predicate), i. e. the stream will stopped once the predicate becomes true.

Unfortunately I did not find anything like that in JRE 8. :-(

Is that planned for JRE 8.1 or JRE 9.0? Or is there a known (and sophisticated) workaround?

Thanks!

-Markus

Comments
Post Details
Added on May 26 2014
1 comment
1,117 views