java – Why doesn’t Stream implement Iterable?

kennytm described because it is not safe to deal Stream how Iterable And Zhong Yu offered an alternative solution allowing you to use Stream as in Iterable, albeit in an unsafe way. You can get the best of both worlds: a Iterable reusable from a Stream which meets all the warranties made by the specification Iterable.

Note: SomeType is not a type parameter here – you need to replace it with a correct type (for example, String) or resort to reflection

Stream stream = ...;
Iterable iterable = stream.collect(toList()):

There is one main drawback:

The benefits of the lazy iteration will be lost. If you plan to iterate over all values ​​in the current thread immediately, any overhead will be negligible. However, if you plan to iterate only partially or in a different thread, this immediate and full iteration could have undesirable consequences.

The big advantage, of course, is that you can reuse Iterablewhile (Iterable) stream::iterator would allow a single use. If the receiving code is repeating the collection multiple times, this is not only necessary, but probably useful for performance.

Leave a comment