Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • It's worth adding that Stream.generate() generates in infinite stream, so the call to limit() is very important here. Commented Jul 5, 2019 at 8:43
  • 1
    @andrebrait even worse, Stream.generate() generates an unordered stream, so there is no guaranty that limit(…) will pick up the first items (as “first” has no meaning here). Or in this specific case, the code may fail with a NoSuchElementException. Commented Feb 15, 2024 at 9:19
  • @Holger ordered/unordered is only gonna make a difference if the stream is parallel. The stream is still gonna just be generated by calling the supplier to get each item, so the order is simply whatever order your function returns items in. I have used it quite a bit, in fact. Even if parallel, IIRC, it won't call your function more than the limit. Can it really result in such an exception? Commented Feb 28, 2024 at 14:33
  • 1
    @andrebrait you’re developing against a contract and the contract of Stream.generate(…).limit(…) is that it may pick arbitrary elements instead of the “first” elements, because “first” has no meaning for an unordered Stream. Even if it happens to do the intended thing in one setup you shouldn’t rely on things that are not guaranteed. Regarding exceptions, I got one right ins the first try: ideone.com/Zy1KkM Commented Feb 28, 2024 at 15:33
  • @Holger I can confirm the exception does happen indeed, but the ordering matter only matters for parallel streams, so I'm gonna agree it's not the most solid implemention, but I wouldn't call it a violation of contract because the contract makes it pretty explicit it's an unordered sequential stream, unless you make it parallel afterwards. But yeah, not very solid. Commented Feb 29, 2024 at 16:18