Java forEach loop to iterate through arrays and collections

The forEach in Java

The foreach loop is generally used for iteration through array elements in different programming languages. The Java provides arrays as well as other collections and there should be some mechanism for going through array elements easily; like the way foreach provides.

This is accomplished by using the enhanced form of the for loop that enables us specifying an array or other collections and working with its elements. The enhanced for loop of Java works just like the foreach loop in that a collection is specified in the for loop. The current element can be assigned to a variable inside the for loop. You may perform a certain action with that element and execution moves to the next item and process goes on until all elements are entertained.

See the following section for the demonstration of going through each element of the array and other collection. I will also show you how to use Java 8 foreach statement after that.

A demo of iterating through each item of array

In this example, an array of six elements is created with numbers. After that, a for loop is used to iterate through each item of the array:

Java foreach array

See online demo and code

The code to iterate through each array element:


A demo of iterating through list items by “forEach”

In this example, each element of the list is accessed and displayed by using an enhanced for loop.

foreach list

See online demo and code

The code of building list and iterating through its items by using for loop:


The forEach statement in Java 8

In Java 8, the new forEach statement is provided that can be used to loop the maps or list etc. You  may loop a list with forEach and lambda expression. A demo code with lambda expression can be as follows:


The output of the program should be:

Iterate, Through, A, List, Collection

The final word

Before you start using the forEach Java 8 function rather than enhanced for loop for iterating through arrays, list, maps or other collection, think carefully about the performance, advantages and disadvantages of both for different scenarios.

You may download the Java 8 here.