Java for-each Loop

Java 5 introduced an for-each loop, which is called a enhanced for each loop. It is used to iterate over elements of an array and the collection.

for-each loop is a shortcut version of for-loop which skips the need to get the iterator and loop over iterator using it’s hasNext() and next() method.

1. Java for-each loop syntax

The general syntax for a for-each loop is as follows:

for(T element : a_collection_or_an_array_of_type_T) 
{
        // This code will be executed once for each element in the collection/array.
        // Each time this code is executed, the element variable holds the reference
        // of the current element in the collection/array
}

2. Java for-each loop example – iterate over array

For example, following snippet of code prints all elements of an integer array numArray.

int[] numArray = {10, 20, 30, 40};

for(int num : numArray) 
{
        System.out.println(num);
}

Program Output.

10
20
30
40

3. Java for each loop example – iterate over collection

Similarly, for a collection type also, program will be written same.

public static void main(String[] args) 
{
	List<Integer> numList = new ArrayList<Integer>();

	numList.add(10);
	numList.add(20);
	numList.add(30);
	numList.add(40);

        //foreach loop
	for(int num : numList) 
        {
	        System.out.println(num);
	}
}

Program Output.

10
20
30
40

4. for each loop with lambda

Since Java 8, we can use lambda expressions as well for a collection type.

Java program to iterate over a list using for each loop and lambda.

public static void main(String[] args) 
{
	List<Integer> numList = new ArrayList<Integer>();

	numList.add(10);
	numList.add(20);
	numList.add(30);
	numList.add(40);

        //foreach loop with lambda
	numList.forEach( item -> System.out.println(item) );

        //Pass function reference
        numList.forEach( System.out::println );
}

Program Output.

10
20
30
40

Drop me your questions related to for-each loop control statement in Java.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial