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

Ivan Gerasimov ivan.gerasimov at oracle.com
Tue Mar 12 23:32:01 UTC 2019


Hello!

Just an observation.

If there were two new subtypes of Iterable introduced:  IterableOnce and 
IterableMultipleTimes, then all existing Iterables could be retrofitted 
to implement one of these.

It wouldn't *automatically* solve the problem of 3rd party API, which 
accepts an Iterable and iterates it multiple times, but would provide a 
means to change that API in a straightforward way.

Also, the static analysis tools could issue a suggestion for code that 
iterates Iterable more than once to switch to IterableMultipleTimes, so 
that it won't be possible to pass in an IterableOnce.

It would also allow to strengthen the specification for 
IterableMultipleTimes and state that all classes implementing it must 
make it possible to obtain multiple iterators.

With kind regards,
Ivan


On 2/28/19 6:43 PM, Stuart Marks 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
>

-- 
With kind regards,
Ivan Gerasimov



More information about the core-libs-dev mailing list