RFR: 8005051: optimized defaults for Iterator.forEachRemaining

David Holmes david.holmes at oracle.com
Sat Apr 27 01:50:07 UTC 2013

On 27/04/2013 1:46 AM, Paul Sandoz wrote:
> On Apr 26, 2013, at 4:37 PM, Peter Levart <peter.levart at gmail.com> wrote:
>> Another "interesting" usage:
>> Iterator<?> i = ...;
>> i.forEachRemaining(e -> {
>>    ...
>>    if (...) {
>>       i.forEachRemaining(dummy -> {}); // drain it
>>    }
>>    ...
>> });
>> It seems that mixing external and internal iteration in the same object is like a box of chocolates. For internal iteration, Iterable.forEach is more suitable than Iterator.forEachRemaining unless the later is specified to have the common state for both external and internal iteration, which means that internal can not be more effective than external.
> Similar observations can apply to Spliterator as well. IIRC many spliterator.forEachRemaining implementations set up state to be fully traversed before looping. However, it is not possible in all cases.
> I think we may have to document that a consumer must not interfere with the current traversal otherwise behaviour is undefined.

Maybe my thinking is not creative enough but to me a method on Iterator 
called forEachRemaining(f) has very clear semantics:

while (it.hasNext()) {

at completion the Iterator is "consumed" there are no elements left.

If f.accept messes with the iterator then it is probably best left 
unspecified as to what might, or might not happen. Then again perhaps 
the interaction of all Iterator methods should be fully spelt out - and 
if we think that is a problem maybe adding methods to Iterator is not 
such a great idea.

But I think this needs to go back to the expert list, if not already there.


> Paul.

More information about the core-libs-dev mailing list