Proposal: JDK-8148917 Enhanced-For Statement Should Allow Streams
Stuart Marks
stuart.marks at oracle.com
Thu Mar 14 01:01:14 UTC 2019
On 3/5/19 12:43 PM, Mike Duigou wrote:
> I don't believe that I would use the proposed enhancement to the for statement.
> For me there is cognitive load reduction in using a symmetrical method for all
> iterations even if they end up being a little more complicated for individual
> cases. Usually, for me, I use streams. Even the more complicated patterns such
> as the presented example will hopefully be familiar because they are repeated in
> many places throughout the code. Truly unusual or unique usages are hopefully
> very rare.
>
> To choose between old style for, enhanced for, or streams based on which warts
> are to be avoided is just frustrating. Mixing idioms or required mixing of
> idioms produces the least satisfying result. Was the use of a particular idiom a
> necessity? A choice? Of no consequence? This gets harder to decode with a larger
> number of available idioms.
I suspect the cases for having mixed-idiom code, as in my example showing a
stream head and a for-loop "tail", are somewhat rare. Maybe less than 5% of
cases. But it least it's there when you need it, without requiring any subtle
workarounds.
I think a more likely benefit is that this can reduce the pressure on the
question of whether an API should return a Collection or a Stream. One
consideration in making such a decision is whether the caller is more likely to
iterate or stream the result. If it's likely the caller will want to iterate,
this tips the decision toward returning a collection. But returning a collection
usually requires creating and storing all the elements, losing laziness, so this
is an uncomfortable tradeoff.
With the ability to iterate a Stream, it's possible for an API to return a
Stream, while letting the caller choose between adding stream operations or
iterating it, without losing laziness.
s'marks
More information about the core-libs-dev
mailing list