在以下情况中我注意到一些奇怪的行为:
迭代器 - >流 - > map() - > iterator() - >迭代
原始迭代器的hasNext()在返回false后被称为额外时间。
这是正常的吗?
package com.test.iterators;
import java.util.Iterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class TestIterator {
private static int counter = 2;
public static void main(String[] args) {
class AdapterIterator implements Iterator<Integer> {
boolean active = true;
@Override
public boolean hasNext() {
System.out.println("hasNext() called");
if (!active) {
System.out.println("Ignoring duplicate call to hasNext!!!!");
return false;
}
boolean hasNext = counter >= 0;
System.out.println("actually has next:" + active);
if (!hasNext) {
active = false;
}
return hasNext;
}
@Override
public Integer next() {
System.out.println("next() called");
return counter--;
}
}
Stream<Integer> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(new AdapterIterator(), 0), false);
stream.map(num -> num + 1).iterator().forEachRemaining(num -> {
System.out.println(num);
});
}
}
如果我删除map()或用count()或collect()替换最终的itearator(),它就可以在没有冗余调用的情况下工作。
输出
hasNext() called
actually has next:true
next() called
3
hasNext() called
actually has next:true
next() called
2
hasNext() called
actually has next:true
next() called
1
hasNext() called
actually has next:true
hasNext() called
Ignoring duplicate call to hasNext!!!!
答案 0 :(得分:1)
是的,这很正常。冗余调用发生在StreamSpliterators.AbstractWrappingSpliterator.fillBuffer()
中,该调用是从hasNext()
返回的迭代器的stream.map(num -> num + 1).iterator()
方法调用的。来自JDK 8来源:
/**
* If the buffer is empty, push elements into the sink chain until
* the source is empty or cancellation is requested.
* @return whether there are elements to consume from the buffer
*/
private boolean fillBuffer() {
while (buffer.count() == 0) {
if (bufferSink.cancellationRequested() || !pusher.getAsBoolean()) {
if (finished)
return false;
else {
bufferSink.end(); // might trigger more elements
finished = true;
}
}
}
return true;
}
对原始pusher.getAsBoolean()
个实例hasNext()
的{{1}}来电AdapterIterator
。如果为true,则将下一个元素添加到bufferSink
并返回true,否则返回false。当原始迭代器用完项目并返回false时,此方法将调用bufferSink.end()
并重试填充缓冲区,从而导致冗余的hasNext()
调用。
在这种情况下,bufferSink.end()
没有效果,第二次尝试填充缓冲区是不必要的,但正如源注释所解释的那样,它可能触发更多元素&#34;在另一种情况下。这只是深入Java 8流复杂内部工作的实现细节。