如果要再次迭代,我们必须缓存来自迭代器的值。至少我们可以将第一次迭代和缓存结合起来:
Iterator<IntWritable> it = getIterator();List<IntWritable> cache = new ArrayList<IntWritable>();// first loop and cachingwhile (it.hasNext()) { IntWritable value = it.next(); doSomethingWithValue(); cache.add(value);}// second loopfor(IntWritable value:cache) { doSomethingElseThatCantBeDoneInFirstLoop(value);}(只需要添加代码答案,就知道您在自己的注释中提到了该解决方案;))
为什么 不进行缓存就不可能做到:
为什么
Iterator是实现接口的
Iterator对象,并且没有一个唯一的要求,即对象实际上存储值。进行两次迭代,您必须重置迭代器(不可能)或克隆它(再次:不可能)。
举一个克隆/重置毫无意义的迭代器为例:
public class Randoms implements Iterator<Double> { private int counter = 10; @Override public boolean hasNext() { return counter > 0; } @Override public boolean next() { count--; return Math.random(); } @Override public boolean remove() { throw new UnsupportedOperationException("delete not supported"); }}


