Forum Stats

  • 3,827,137 Users
  • 2,260,744 Discussions
  • 7,897,181 Comments

Discussions

How to stop an infinite Stream?

Markus KARG
Markus KARG Member Posts: 99
edited Jun 6, 2014 2:21PM in Java 8 Questions

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

gbishop

Answers