Question: 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?

Answer: 
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.
**Collections**

If `channels` are some kind of [`Iterable`](https://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html), then you can write the loop as

```
for(Channel c : channels) {
  if(c.getTYPE().equals(type) 
    || type.equals(ChannelTypeEnum.ALL)) {
       return true;
  }
}
return false;

```

No need to increment position if you're using that position only for iteration to the next element.

This is only shorthand - code for using an iterator as stated in comments - so it will not gain much in terms of performance but adds clarity to your code. Implementing your *own* iterator as you did in code above is not neccessary if the type of your `channels` already *is* a `Collection` and implements `Iterable`