Iterating over a list in Java

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:

List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);

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.

for(int i=0; i<numbers.size(); i++) {
System.out.print(i+ " ");
}
view raw ForBasic.java hosted with ❤ by GitHub

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.

for(int i: numbers) {
System.out.print(i+ " ");
}

Modifying the list while iterating on it with the above constructs leads to ConcurrentModificationException.

3. Iterators

Iterator is widely used in Java Collections. It is specially useful when you need to modify the list that is being iterated on.

Iterator<Integer> itr = numbers.iterator();
while(itr.hasNext()) {
int i = itr.next();
System.out.print(i+ " ");
if(i==3) {
itr.remove();
}
}

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.

ListIterator<Integer> litr = numbers.listIterator();
while(litr.hasNext()) {
int i = litr.next();
System.out.print(i+ " ");
}
while (litr.hasPrevious()) {
int i= litr.previous();
System.out.print(i+ " ");
}

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.

numbers.forEach(System.out::println);

5. Streams

Apart from this you can convert the collection to a stream and use the forEach on the stream.

numbers.stream().forEach((i) -> System.out.println(i));

Conclusion

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.

Reference:

https://www.baeldung.com/java-iterate-list