Home » Core Java » Java 8 forEach Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java 8 forEach Example

Hello readers, Java8 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 List, Set and Map using the Java forEach() method.

1. Introduction

From Java 8 on, developers can iterate over a List or any Collection without using any loop in Java programming. The new Stream class provides a forEach() method, which can be used to loop over all or the selected elements of List, Set, and Map. forEach() method 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 work on 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, developers 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() Method Signature

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.

public interface Iterable<T> {
…
default void forEach(Consumer<super T> action) {
	for(T t : this) {
	    action.accept(t);
    }
}

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 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 parallem code, all they need to do is call a parallelStream() method

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

2. Java8 forEach Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

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

Fig. 1: Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

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

Fig. 2: 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.

Fig. 3: 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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<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 Program to use forEach() function in Java8

Here is my 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

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();
	}
}

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

# 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

That’s all for this post. Happy Learning!

6. Conclusion

That’s all about how to use the forEach() in Java8. 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.

7. Download the Eclipse Project

This was an example of forEach() method introduced in Java8.

Download
You can download the full source code of this example here: Java8Foreach
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of