java 迭代器的hasnext,流到迭代器的Java 8 Iterator导致对hasNext()的冗余调用

I notice a bit of a strange behavior in the following scenario:

Iterator -> Stream -> map() -> iterator() -> iterate

The hasNext() of the original iterator is called an additional time after having already returned false.

Is this normal?

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 {

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 stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(new AdapterIterator(), 0), false);

stream.map(num -> num + 1).iterator().forEachRemaining(num -> {

System.out.println(num);

});

}

}

If I either remove the map() or replace the final itearator() with something like count() or collect() it works without the redundant call.

Output

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

解决方案

Yes, this is normal. The redundant call happens in StreamSpliterators.AbstractWrappingSpliterator.fillBuffer(), which is called from the hasNext() method of the iterator returned by stream.map(num -> num + 1).iterator(). From the JDK 8 source:

/**

* 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;

}

The call to pusher.getAsBoolean() calls hasNext() on the original AdapterIterator instance. If true, it adds the next element to bufferSink and returns true, otherwise it returns false. When the original iterator runs out of items and it returns false, this method calls bufferSink.end() and retries filling the buffer, which leads to the redundant hasNext() call.

In this case, bufferSink.end() has no effect and the second attempt to fill the buffer is unnecessary, but as the source comment explains, it "might trigger more elements" in another situation. This is just an implementation detail buried deep in the complex inner workings of Java 8 streams.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值