How to safely consume Java Streams safely without isFinite() and isOrdered() methods?

后端 未结 1 916
再見小時候
再見小時候 2020-12-31 00:08

There is the question on whether java methods should return Collections or Streams, in which Brian Goetz answers that even for finite sequences, Streams should usually be pr

相关标签:
1条回答
  • 2020-12-31 01:00

    After looking at things a bit (some experimentation and here) as far as I see, there is no way to know definitely whether a stream is finite or not.

    More than that, sometimes even it is not determined except at runtime (such as in java 11 - IntStream.generate(() -> 1).takeWhile(x -> externalCondition(x))).

    What you can do is:

    1. You can find out with certainty if it is finite, in a few ways (notice that receiving false on these does not mean it is infinite, only that it may be so):

      1. stream.spliterator().getExactSizeIfKnown() - if this has an known exact size, it is finite, otherwise it will return -1.

      2. stream.spliterator().hasCharacteristics(Spliterator.SIZED) - if it is SIZED will return true.

    2. You can safe-guard yourself, by assuming the worst (depends on your case).

      1. stream.sequential()/stream.parallel() - explicitly set your preferred consumption type.
      2. With potentially infinite stream, assume your worst case on each scenario.

        1. For example assume you want listen to a stream of tweets until you find one by Venkat - it is a potentially infinite operation, but you'd like to wait until such a tweet is found. So in this case, simply go for stream.filter(tweet -> isByVenkat(tweet)).findAny() - it will iterate until such a tweet comes along (or forever).
        2. A different scenario, and probably the more common one, is wanting to do something on all the elements, or only to try a certain amount of time (similar to timeout). For this, I'd recommend always calling stream.limit(x) before calling your operation (collect or allMatch or similar) where x is the amount of tries you're willing to tolerate.

    After all this, I'll just mention that I think returning a stream is generally not a good idea, and I'd try to avoid it unless there are large benefits.

    0 讨论(0)
提交回复
热议问题