Sometimes, Spliterator.forEachRemaining has much more optimized implementation, compared to Spliterator.tryAdvance. For example, if a Stream.spliterator() called for a stream that has intermediate operations, tryAdvance() may buffer intermediate elements while forEachRemaining() just delegates to the wrapAndCopyInto (see StreamSpliterators.AbstractWrappingSpliterator and its inheritors).
Spliterators.iterator() methods (used in particular by Stream.iterator()) provide adapter iterators that delegate to the supplied spliterator. Unfortunately, they don't have a specialized implementation for Iterator::forEachRemaining. As a result, a default implementation is used that delegates to hasNext/next, which in turn causes the delegation to tryAdvance. It's quite simple to implement Iterator::forEachRemaining here, taking advantage of possible spliterator optimizations if the iterator client decides to use forEachRemaining.
Spliterators.iterator() methods (used in particular by Stream.iterator()) provide adapter iterators that delegate to the supplied spliterator. Unfortunately, they don't have a specialized implementation for Iterator::forEachRemaining. As a result, a default implementation is used that delegates to hasNext/next, which in turn causes the delegation to tryAdvance. It's quite simple to implement Iterator::forEachRemaining here, taking advantage of possible spliterator optimizations if the iterator client decides to use forEachRemaining.
- relates to
-
JDK-8267359 Stream.flatMap() consumes entire flatmapped stream when Stream.iterator() is called
-
- Closed
-