Tips & Tricks: How to iterate over a collection using the for loop.

Most Java programmers are aware of how to initialize and use an iterator utilizing the basic while loop. In most cases developers will iterate over a collection for every element in it using the follow generic code:

Iterator lIter = myList.iterator();
while(lIter.hasNext()) {
    ... // some logic

However it is surprising how many developers don’t know how to use the iterator in a for loop. You might wonder why would you want to use the for loop? Simply put you limit the scope of your iterator to the loop itself and it condenses the code to a single line. Rewriting the above iterator would look like:

for(Iterator lIter = myList.iterator(); lIter.hasNext(); ) {
    ... // some logic

There you have it, how to iterate over all the elements of a collection using an iterator and the for loop.

// Java // Tips & Tricks //

Comments & Questions

Add Your Comment