Iterating over a list is one of the most common tasks that is required for writing any program. This post will focus on the different ways of iterating over a List in java. It will cover the aspects that should be considered while iterating over the list using a particular method.
For all the examples below let us consider a list of Integers. You can initialise it as follows:
1. Basic For Loop
You can iterate over a list of collections with a simple for loop, like in any language. This for loop has three parts to it, the initialising statement, the loop condition check statement and the increment statement.
2. Enhanced For Loop
The enhanced for loop is a more compact form of basic for loop that can be used to iterate over a list.
Modifying the list while iterating on it with the above constructs leads to ConcurrentModificationException.
Iterator is widely used in Java Collections. It is specially useful when you need to modify the list that is being iterated on.
The two important methods for an iterator are hasNext() and next(). The above snippet shows how these two can be used to iterate over the list.
There is also a listIterator in Java. This can be used to traverse the list in both directions.
4. ForEach (Iterable)
Java 8 introduced lambdas. This led to an addition of forEach function which can be used to iterate over a collection easily.
There is a forEach method in the Iterable interface.
Apart from this you can convert the collection to a stream and use the forEach on the stream.
This post covers a few different ways to iterate over a list in Java, and when should you prefer which. All of the code is available on Github.