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: 
what do you mean by "using while loop twice" ? if you are concerned whether you iterate twice over the collection, then it doesn't seem so to me. the iterator keeps a position pointer that in both methods only seems to go forward. so while you do have nested loops (one in the application code, on in hasNext() method) they do not fetch the same item
**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`