Search code examples
javacollectionsiterator

what is the performance efficient method for iterate java collection?


I want to know about iterator design pattern and found on following tutorial.

http://www.journaldev.com/1716/iterator-design-pattern-in-java-example-tutorial

Following is the code for hasNext() and next() methods.

@Override
public boolean hasNext() {
    while (position < channels.size()) {
        Channel c = channels.get(position);
            if (c.getTYPE().equals(type) ||     type.equals(ChannelTypeEnum.ALL)) {
                return true;
            } else
                position++;
        }
    return false;
}

@Override
public Channel next() {
    Channel c = channels.get(position);
    position++;
    return c;
}

and using above method collection iterated is

while (baseIterator.hasNext()) {
    Channel c = baseIterator.next();
    System.out.println(c.toString());
}

If we are using hasNext() and next() methods it look like we are using while loop twice.

is this ok when application is small enough and performance is the priority? or there can be optimized code?


Solution

  • The performance of Iterator depends on its implementation. Every Java collection has its own iterator implementation, so the performance will vary. Usually hasNext and next methods have no loops. The code you are showing is some special iterator from the tutorial which iterates while performing the filtering. While you have two nested loops, you actually traverse the underlying collection channels only once as position constantly increases from 0 to channels.size(). The hasNext() internal loop is necessary to skip the unwanted items, but it does not add the computational difficulty. The overall difficulty of such iteration is O(channels.size()).

    Note that this iterator implementation breaks the Iterator interface contract. First it does not throw NoSuchElementException at the end of the iteration. Second, if you call next() several times without calling hasNext() you will have different results. Thus I would not recommend use the samples from this tutorial in the real code.