Proposal: JDK-8148917 Enhanced-For Statement Should Allow Streams

Stuart Marks stuart.marks at
Tue Mar 12 21:45:12 UTC 2019

Hi Remi,

> Stream.iterator() can be really really slow, it uses a pull semantics while
> the whole Stream push values. When designing it, the lambda EG saw it as an
> "escape hatch" in order to interropt with a legacy code than require an
> Iterator and not more.

If Stream.iterator() is slow, then perhaps it needs to be optimized. Tagir had 
some ideas for how to do that. Of course, I don't know if that's exactly the 
right way; some additional investigation should be done. But poor performance 
relative to Spliterator.tryAdvance() or forEachRemaining() shouldn't be an 
argument against doing this. People repeatedly bump into the gap in the 
programming model between streams and the enhanced-for loop, and it's time to 
fill it in.

> This proposal has the side effect of making Stream more different from its
> primitive counterpart IntStream, LongStream and DoubleStream which may be
> problematic because we are trying to introduce reified generics as part of
> Valhalla (there is a recent mail of Brian about not adding methods to
> OptionalInt for the same reason).

Well, yes, I think that it means that Stream evolves somewhat independently of 
Int/Long/DoubleStream, but I don't see that this imposes an impediment on 
generic specialization in Valhalla. In that world, Stream<int> should (mostly) 
just work. It may also be possible in a specialized world to add the specific 
things from IntStream (such as sum() and max()) to Stream<int>.

> And, the real issue is how to deal with checked exceptions inside the Stream
> API, i would prefer to fix that issue instead of trying to find a way to
> workaround it.

Well I'd like to have a solution for checked exceptions as well, but there 
doesn't appear to be one on the horizon. I mean, there are some ideas floating 
around, but nobody is working on them as far as I know.

But checked exceptions aren't the only reason to prefer iteration in some cases; 
loops offer more flexible control flow (break/continue) and easier handling of 
side effects. The Streams+IterableOnce feature benefits these cases as well as 
exception handling.


More information about the core-libs-dev mailing list