Core Java

For Each Loop Java 8 Example

In this post, we feature a comprehensive For Each Loop Java 8 Example. Foreach method, it is the enhanced for loop that was introduced in Java since J2SE 5.0.

Java 8 came up with a new feature to iterate over the Collection classes, by using the forEach() method of the Iterable interface or by using the new Stream class.

In this tutorial, we will learn how to iterate over a List, Set and Map using the Java forEach method.

1. For Each Loop in Java – Introduction

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse a collection of elements including arrays.

From Java 8 and on, developers can iterate over a List or any Collection without using any loop in Java programming, because of this enhanced for loop. The new Stream class provides a forEach method, which can be used to loop over all of the selected elements of List, Set, and Map. This enhanced loop called forEach() provides several advantages over the traditional for loop e.g. We can execute it in parallel by just using a Parallel Stream instead of Regular Stream.

 
Since developers are working with stream, it allows them to filter and map the elements. Once they are done with filtering and mapping, they can use the forEach() method to work over them. We can even use method reference and lambda expression inside the forEach() method, resulting in more understandable and brief code.

An important thing about the forEach() method is that it is a Terminal Operation, which means developers cannot reuse the Stream after calling this method. It will throw IllegalStateException if developers try to call another method on this Stream.

Do remember, you can also call the forEach() method without obtaining the Stream from the List, e.g. sList.forEach(), because the forEach() method is also defined in Iterable interface, but obtaining Stream gives them further choices e.g. filtering, mapping or flattening etc.

1.1 forEach Signature in Java

We can write this useful tool in two ways:

  • As a method
  • As a simple for loop

As a method, in Iterable interface, the forEach() method takes a single parameter which is a functional interface. Developers can pass the Lambda Expression as an argument and it can be coded as shown below.

1
2
3
4
5
6
7
public interface Iterable<T> {
default void forEach(Consumer<super T> action) {
    for(T t : this) {
        action.accept(t);
    }
}

As for a simple for loop:

for(data_type item : collection) {
    ...
}
  • collection  is an array variable or collection which you have to loop through.
  • item  is an item from the collection.

1.2 Things to Remember

  • forEach() is a terminal operation, which means once calling this method on a stream, we cannot call another method. It will result in a runtime exception
  • When developers call the forEach() method on a parallel stream, the iteration order  is not guaranteed, but developers can ensure that ordering by calling the forEachOrdered() method
  • There are two forEach() methods in Java8, one defined inside the Iterable and other inside the java.util.stream.Stream class. If the purpose of forEach() is just iteration then we can directly call it (i.e. list.forEach() or set.forEach() etc). But if developers want to do some operations then get the stream first and then do that operation and finally call forEach() method
  • Use of forEach() results in a readable and cleaner code
  • Favor using forEach() with Streams because streams are slow and not evaluated until a terminal operation is called

1.3 Java For Loop enhanced – advantages

There are several advantages of using the forEach() statement over the traditional for loop in Java e.g.

  • More manageable code
  • Developers can pass the Lambda Expression, which gives them the substantial flexibility to change what they do in the loop
  • forEach() looping can be made parallel with minimum effort i.e. Without writing a single line of parallel code, all they need to do is call a parallelStream() method

1.4 For vs forEach in Java

  • Use: Between for and foreach is that, in the case of indexable objects, you do not have access to the index.
  • Performance: When accessing collections, a foreach is significantly faster than the for loop’s array access. Αt least with primitive and wrapper-arrays when accessing arrays, access via indexes is dramatically faster.

Now, open up the Eclipse Ide and let’s see how to iterate over a List using the forEach() method of Java8.

2. For Each Loop Java 8 Example

2.1 Technologies used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!

For Each Loop Java - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show you how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

For Each Loop Java - Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next button to go ahead.

For Each Loop Java - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

1
2
3
4
5
6
7
    <modelVersion>4.0.0</modelVersion>
    <groupId>Java8Foreach</groupId>
    <artifactId>Java8Foreach</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to show the operation of forEach() method. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: ForEachDemo. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (ForEachDemo.java)
Fig. 8: Java Class (ForEachDemo.java)

3.1.1 forEach function in Java 8

Here is a sample program to show how to use the forEach() statement to iterate over every element of a List, Set, Map or Stream in Java.

ForEachDemo.java

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
package com.jcg.java;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class ForEachDemo {
 
    /**** EXAMPLE METHOD #1 ****/
    private static void iterateListUsingForEach() {
 
        /*** List Instantiation :: Type #1 ***/
        List<String> cList = new ArrayList<String>();
        cList.add("India");
        cList.add("USA");
        cList.add("Japan");
        cList.add("Canada");
        cList.add("Singapore");
 
        /*** List Instantiation :: Type #2 ***/
        // List<String> cList = Arrays.asList("India", "USA", "Japan", "Canada", "Singapore");
 
        System.out.println("<------------Iterating List By Passing Lambda Expression-------------->");
        cList.forEach(cName -> System.out.println(cName));
 
        System.out.println();
 
        // You Can Even Replace Lambda Expression With Method Reference. Here We Are Passing The Lambda Parameter As It Is To The Method.
        System.out.println("<------------Iterating List By Passing Method Reference--------------->");
        cList.forEach(System.out::println);
 
        System.out.println();
 
        // There Is One More Foreach() Method On Stream Class, Which Operates On Stream And Allows You To Use Various Stream Methods E.g. filter(), mapToInt() Etc.
        System.out.println("<------------Printing Elements Of List By Using 'forEach' Method------------>");
        cList.stream().forEach(System.out::println);
 
        System.out.println();
 
        // Using Stream API & Filter.
        System.out.println("<------------Printing Specific Element From List By Using Stream & Filter------------>");
        cList.stream().filter(cname -> cname.startsWith("S")).forEach(System.out::println);
 
        System.out.println();
 
        // You Can Also Use 'forEach' With Parallel Stream. In This, The Order Will Not Be Guaranteed.
        System.out.println("<------------Printing Elements Of List By Using Parallel Stream------------>");
        cList.parallelStream().forEach(cName -> System.out.println(cName));
    }
 
    /**** EXAMPLE METHOD #2 ****/
    private static void iterateSetUsingForEach() {
 
        Set <String> persons = new HashSet<String> ();
        persons.add("Java Geek");
        persons.add("Sam");
        persons.add("David");
        persons.add("April O' Neil");
        persons.add("Albus");
 
        System.out.println("<------------Iterating Set By Passing Lambda Expression-------------->");
        persons.forEach((pName) -> System.out.println(pName));
 
        System.out.println();
 
        System.out.println("<------------Iterating Set By Passing Method Reference--------------->");
        persons.forEach(System.out::println);
    }
 
    /**** EXAMPLE METHOD #3 ****/
    private static void iterateMapUsingForEach() {
 
        Map<String, String> days = new HashMap<String, String>();
        days.put("1", "SUNDAY");
        days.put("2", "MONDAY");
        days.put("3", "TUESDAY");
        days.put("4", "WEDNESDAY");
        days.put("5", "THURSDAY");
        days.put("6", "FRIDAY");
        days.put("7", "SATURDAY");
 
        System.out.println("<------------Iterating Map Using 'forEach' Method--------------->");
        days.forEach((key, value) -> {
            System.out.println(key + " : " + value);
        });
    }
 
    public static void main(String[] args) {
 
        // Iterate Through List Using 'forEach' Method
        iterateListUsingForEach();
 
        System.out.println();
 
        // Iterate Through Set Using 'forEach' Method
        iterateSetUsingForEach();
 
        System.out.println();
 
        // Iterate Through Map Using 'forEach' Method
        iterateMapUsingForEach();
    }
}

3.1.2 For Each loop before Java 8

Here is a sample program to show how to use a for-each loop with a List, Set, Map in Java.

For_each_loop.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class For_each_loop {
	/**** EXAMPLE METHOD #1 ****/
	private static void ListUsingForEach() {

		/*** List Instantiation :: Type #1 ***/
		List cList = new ArrayList();
		cList.add("India");
		cList.add("USA");
		cList.add("Japan");
		cList.add("Canada");
		cList.add("Singapore");

		for(String clist: cList) {
			 System.out.println(clist);
		}
		
		
	}
	private static void SetUsingForEach() {

		Set  persons = new HashSet ();
		persons.add("Java Geek");
		persons.add("Sam");
		persons.add("David");
		persons.add("April O' Neil");
		persons.add("Albus");
		
		for(String person: persons) {
			 System.out.println(person);
		}
		
		}
	private static void MapUsingForEach() {

		Map days = new HashMap();
		days.put("1", "SUNDAY");
		days.put("2", "MONDAY");
		days.put("3", "TUESDAY");
		days.put("4", "WEDNESDAY");
		days.put("5", "THURSDAY");
		days.put("6", "FRIDAY");
		days.put("7", "SATURDAY");
		
		for(Map.Entry day: days.entrySet()) {
			 System.out.println(day);
		}
		
	}



	public static void main(String[] args) {

		System.out.println("List using For each loop :");

		ListUsingForEach();

		System.out.println();
		
		System.out.println("Set Using For Each :");
		
		SetUsingForEach();
		
		System.out.println();
		
		
		System.out.println("Map Using For Each :");
		 MapUsingForEach();

		
	}
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

Developers can write more code by following the above techniques. I suggest you experiment with different stream methods to learn more. The above code shows the following logs as output.

Output of forEach() method

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Logs for 'EXAMPLE METHOD #1' #
================================
<------------Iterating List By Passing Lambda Expression-------------->
India
USA
Japan
Canada
Singapore
 
<------------Iterating List By Passing Method Reference--------------->
India
USA
Japan
Canada
Singapore
 
<------------Printing Elements Of List By Using 'forEach' Method------------>
India
USA
Japan
Canada
Singapore
 
<------------Printing Specific Element From List By Using Stream & Filter------------>
Singapore
 
<------------Printing Elements Of List By Using Parallel Stream------------>
Japan
India
Canada
USA
Singapore
 
# Logs for 'EXAMPLE METHOD #2' #
================================
<------------Iterating Set By Passing Lambda Expression-------------->
April O' Neil
Albus
Java Geek
David
Sam
 
<------------Iterating Set By Passing Method Reference--------------->
April O' Neil
Albus
Java Geek
David
Sam
 
# Logs for 'EXAMPLE METHOD #3' #
================================
<------------Iterating Map Using 'forEach' Method--------------->
1 : SUNDAY
2 : MONDAY
3 : TUESDAY
4 : WEDNESDAY
5 : THURSDAY
6 : FRIDAY
7 : SATURDAY

Output of for-each loop

 
List using For each loop :
India
USA
Japan
Canada
Singapore

Set Using For Each :
April O' Neil
Albus
Java Geek
David
Sam

Map Using For Each :
1=SUNDAY
2=MONDAY
3=TUESDAY
4=WEDNESDAY
5=THURSDAY
6=FRIDAY
7=SATURDAY

That’s all for this post. Happy Learning!

6. Summary

As we stated at the beginning, forEach is an enhanced for loop and it was introduced in Java since J2SE 5.0. In this article, we learned how to use the For Each loop in Java 8.

By following this example, developers can easily get to speed with respect to using the forEach() method to iterate over any Collection, List, Set or Queue in Java.

8. Download the Eclipse Project

This was a For Each Loop Java 8 Example.

Download
You can download the full source code of this example here: For Each Loop Java 8 Example

Last updated on Apr. 29th, 2021

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
mary
mary
4 years ago

Please fix the code below:

[ List cList = new ArrayList ();]
[ Set persons = new HashSet ();]
[Map days = new HashMap ();]
[ for(Map.Entry day: days.entrySet()) {]

Abdo
4 years ago

Indeed, I’m a big fan of Java 8 foreach method! Great article, your are doing great… Keep it up

Back to top button