For Each Loop Java 8 Example (original) (raw)

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, 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.

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

As for a simple for loop:

for(data_type item : collection) { ... }

1.2 Things to Remember

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.

1.4 For vs forEach in Java

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

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

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

001002003004005006007008009010011012013014015016017018019020021022023024025026027028029030031032033034035036037038039040041042043044045046047048049050051052053054055056057058059060061062063064065066067068069070071072073074075076077078079080081082083084085086087088089090091092093094095096097098099100101102103104105106107 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 cList = new ArrayList(); cList.add("India"); cList.add("USA"); cList.add("Japan"); cList.add("Canada"); cList.add("Singapore"); /*** List Instantiation :: Type #2 ***/ System.out.println("<------------Iterating List By Passing Lambda Expression-------------->"); cList.forEach(cName -> System.out.println(cName)); System.out.println(); System.out.println("<------------Iterating List By Passing Method Reference--------------->"); cList.forEach(System.out::println); System.out.println(); System.out.println("<------------Printing Elements Of List By Using 'forEach' Method------------>"); cList.stream().forEach(System.out::println); System.out.println(); 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(); 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 persons = new HashSet (); 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) { iterateListUsingForEach(); System.out.println(); iterateSetUsingForEach(); System.out.println(); 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

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 # Logs for 'EXAMPLE METHOD #1' #================================<------------Iterating List By Passing Lambda Expression-------------->IndiaUSAJapanCanadaSingapore<------------Iterating List By Passing Method Reference--------------->IndiaUSAJapanCanadaSingapore<------------Printing Elements Of List By Using 'forEach' Method------------>IndiaUSAJapanCanadaSingapore<------------Printing Specific Element From List By Using Stream & Filter------------>Singapore<------------Printing Elements Of List By Using Parallel Stream------------>JapanIndiaCanadaUSASingapore# Logs for 'EXAMPLE METHOD #2' #================================<------------Iterating Set By Passing Lambda Expression-------------->April O' NeilAlbusJava GeekDavidSam<------------Iterating Set By Passing Method Reference--------------->April O' NeilAlbusJava GeekDavidSam# Logs for 'EXAMPLE METHOD #3' #================================<------------Iterating Map Using 'forEach' Method--------------->1 : SUNDAY2 : MONDAY3 : TUESDAY4 : WEDNESDAY5 : THURSDAY6 : FRIDAY7 : 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.

Last updated on Apr. 29th, 2021

Photo of 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).