I don't understand why we need IterableOnce ? Was: Proposal: JDK-8148917 Enhanced-For Statement Should Allow Streams
Peter Levart
peter.levart at gmail.com
Fri Mar 15 08:31:10 UTC 2019
On 3/15/19 9:24 AM, Peter Levart wrote:
>
>
> On 3/15/19 9:03 AM, forax at univ-mlv.fr wrote:
>>> * @since 13
>>> */
>>> interface Once {}
>>>
>>>
>>> What do you think of that?
>> It's not clear to me if an annotation, available at runtime, is not a better fit.
>> Anyway, i'm not sure not sure introducing such interface/annotation worth its maintenance cost, as you said the use case is pretty narrow.
>>
>
> It is narrow, but in a situation like that, where you want to code an
> optimal generic algorithm and all you have access to is an Iterable,
> there's no other way (short of providing additional methods, which is
> ugly). Just think of this situation. You have to decide upfront if you
> need to buffer the elements obtained from 1st iteration or not, but
> 1st iteration always succeeds...
Ok, I confess, there is a way to do it without marker interface, but is
ugly:
Iterator<T> iterator1 = iterable.iterator();
Iterator<T> iterator2;
try {
iterator2 = iterable.iterator();
} catch (IllegalStateException e) {
// we have one-shot iterable
iterator2 = null;
}
if (iterator2 == null) {
// buffer elements of iterator1 while iterating for 2nd and
subsequent iterations
...
} else {
// consume iterator1, then iterator2, then create more iterators
for subsequent iterations
...
}
Peter
More information about the core-libs-dev
mailing list