4

我注意到以下场景中的一些奇怪行为:

迭代器 -> 流 -> map() -> 迭代器() -> 迭代

原始迭代器的 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() 或将最终的 itearator() 替换为 count() 或 collect() 之类的东西,它就可以在没有冗余调用的情况下工作。

输出

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!!!!
4

1 回答 1

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()调用。如果为真,则添加下一个元素并返回真,否则返回假。当原始迭代器用完项目并返回 false 时,此方法会调用并重试填充缓冲区,这会导致冗余调用。hasNext()AdapterIteratorbufferSinkbufferSink.end()hasNext()

在这种情况下,bufferSink.end()没有效果,并且第二次尝试填充缓冲区是不必要的,但正如源注释所解释的那样,在另一种情况下它“可能会触发更多元素”。这只是隐藏在 Java 8 流的复杂内部工作原理中的一个实现细节。

于 2015-04-21T20:08:30.933 回答