Java Iterator Size counter(final Iterator iterator)

Here you can find the source of counter(final Iterator iterator)

Description

Count the number of objects in an iterator.

License

Apache License

Parameter

Parameter Description
iterator the iterator to count

Return

the number of objects in the iterator

Declaration

public static long counter(final Iterator iterator) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Iterator;

import java.util.NoSuchElementException;

public class Main {
    /**//from  w w w  .  j a v a  2 s  .co  m
     * Count the number of objects in an iterator.
     * This will exhaust the iterator.
     * Note that the try/catch model is not "acceptable Java," but is more efficient given the architecture of AbstractPipe.
     *
     * @param iterator the iterator to count
     * @return the number of objects in the iterator
     */
    public static long counter(final Iterator iterator) {
        long counter = 0;
        try {
            while (true) {
                iterator.next();
                counter++;
            }
        } catch (final NoSuchElementException e) {
        }
        return counter;
    }
}

Related

  1. count(final Iterator iterator)
  2. count(Iterator triples)
  3. count(Iterator iterator)
  4. count(Iterator it)
  5. size(final Iterator iter)
  6. size(Iterator source)
  7. size(Iterator iterator)
  8. size(Iterator iterator)