Iterating Over Collections In Java

By Harrison Brock / January 29, 2019

Iteration is the most common operations done on a collection. For example, you may want to go through all the student grades to find who has the highest test scores.

In Java we have four methods for iterating over a collection, the methods are the for loop, iterator, forEach and lambda expressions.

Setup Collection

Here we create an ArrayList with the names of some employees.

Iterating With A For Loop

This is the first method that most developers learn when starting to program. This method uses a counter variable named index and moves from the first item in the collection to the last item in the collection.

The only downside to using this method is that it cannot be used on collections like Set. This is because Set is not an index base collection.

Output:

Iterating With An Iterator

This method loops over the items in the collection and uses the next method to get the item.

Output:

Iterating With The Enhanced For Loop

The enhanced for loop is using the iterator method behind the scenes. Using the technique is much easier to read and is used more often.

Output:

Iterating With The ForEach

With this method, the developer does not have to write code to iterate over the collection because Java does it for us. Instead, we specify what to do in each iteration.

Output:

Conclusion

You have seen different ways to iterate over a collection. Nowadays the Enhanced For Loop and the forEach methods are the most simple way for iterating over collections in Java.

 

About the author

Harrison Brock