One more alternative which could be considered (though it requires a language change) is to allow the inference of Iterable<T> type for enhanced for when iteration value is a function expression and iteration parameter type is explicitly specified as T. In this case for(T t : stream::iterator) {} would be a valid syntax. Also people could use enhanced for with any iterator they already have like for(T t : () -> iterator) {}. Instead of for (; it.hasNext() ; ) { T t = it.next(); ... }. It looks better than allowing to specify iterator directly (like for(T t : stream.iterator())) as this could break some programs where the same class implements Iterator and Iterable.
With best regards, Tagir Valeev. On Fri, Mar 1, 2019 at 9:47 AM Stuart Marks <stuart.ma...@oracle.com> wrote: > > Hi all, > > Please review and comment on this proposal to allow Stream instances to be > used > in enhanced-for ("for-each") loops. > > Abstract > > Occasionally it's useful to iterate a Stream using a conventional loop. > However, > the Stream interface doesn't implement Iterable, and therefore streams cannot > be > used with the enhanced-for statement. This is a proposal to remedy that > situation by introducing a new interface IterableOnce that is a subtype of > Iterable, and then retrofitting the Stream interface to implement it. Other > JDK > classes will also be retrofitted to implement IterableOnce. > > Full Proposal: > > http://cr.openjdk.java.net/~smarks/reviews/8148917/IterableOnce0.html > > Bug report: > > https://bugs.openjdk.java.net/browse/JDK-8148917 > > Webrev: > > http://cr.openjdk.java.net/~smarks/reviews/8148917/webrev.0/ > > Note, this changeset isn't ready to push yet. In particular, it has no tests > yet. However, the implementation is so simple that I figured I should include > it. Comments on the specification wording are also welcome. > > Thanks, > > s'marks