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

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.

Tags

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
5 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
5 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