好吧,你可以简单地使用
iterator instanceof PrimitiveIterator.OfInt
测试,但当预期操作
forEachRemaining
IntConsumer
将传递给
PrimitiveIterator.OfInt
为了高效处理和
Consumer<Integer>
基本迭代器。OFIT
如果你在一个类中实现了这两个,你根本不需要执行测试,迭代器会帮你:
public static void main(String[] args) {
System.out.println("with Collection (of Integer boxes)");
filterAndPrint(Arrays.asList(1, 2, 3), i -> i>2);
System.out.println("with IntStream (using primitive int values)");
filterAndPrint(() -> IntStream.range(1, 4).iterator(), i -> i>2);
}
interface LoggingUnboxingIntConsumer extends IntConsumer, Consumer<Integer> {
@Override default void accept(Integer t) {
System.out.println(" unboxing " + t);
accept(t.intValue());
}
}
public static void filterAndPrint(Iterable<Integer> i, IntPredicate p) {
i.iterator().forEachRemaining((LoggingUnboxingIntConsumer) (int value) -> {
if(p.test(value)) System.out.println(" value "+value+" matches");
});
}
with Collection (of Integer boxes)
unboxing 1
unboxing 2
unboxing 3
value 3 matches
with IntStream (using primitive int values)
value 3 matches
这表明尽可能避免装箱操作。这是
the contract of
PrimitiveIterator.OfInt.forEachRemaining(Consumer<? super Integer>)
这不适用于通过
hasNext()
next()
,但由于您的代码应该执行
PrimitiveIterable.OfInt
只是,最初的步骤是唯一需要进行适应的地方
public static PrimitiveIterator.OfInt adapt(Iterator<Integer> it) {
return it instanceof PrimitiveIterator.OfInt? (PrimitiveIterator.OfInt)it:
new PrimitiveIterator.OfInt() {
public int nextInt() { return it.next(); }
public boolean hasNext() { return it.hasNext(); }
public Integer next() { return it.next(); }
};
}
Iterable
,例如。
public static FilterIteratorInt filter(Iterable<Integer> iter, IntPredicate filter) {
return new FilterIteratorInt(adapt(iter.iterator()), filter);
}
但请注意,这个迭代器组合看起来非常像流API(或
IntStream