What is the best way to get the count/length/size of an iterator?

后端 未结 9 1118
青春惊慌失措
青春惊慌失措 2020-12-03 00:01

Is there a \"computationally\" quick way to get the count of an iterator?

int i = 0;
for ( ; some_iterator.hasNext() ; ++i ) some_iterator.next();

9条回答
  •  忘掉有多难
    2020-12-03 01:01

    for Java 8 you could use,

    public static int getIteratorSize(Iterator iterator){
            AtomicInteger count = new AtomicInteger(0);
            iterator.forEachRemaining(element -> {
                count.incrementAndGet();
            });
            return count.get();
        }
    

提交回复
热议问题