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) {
...
}
-
collectionis an array variable or collection which you have to loop through. -
itemis 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 theforEachOrdered()method - There are two
forEach()methods in Java8, one defined inside theIterableand other inside thejava.util.stream.Streamclass. If the purpose offorEach()is just iteration then we can directly call it (i.e.list.forEach()orset.forEach()etc). But if developers want to do some operations then get the stream first and then do that operation and finally callforEach()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 aparallelStream()method
1.4 For vs forEach in Java
- Use: Between
forandforeachis that, in the case of indexable objects, you do not have access to the index. - Performance: When accessing collections, a
foreachis significantly faster than theforloop’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!



Please fix the code below:
[ List cList = new ArrayList ();]
[ Set persons = new HashSet ();]
[Map days = new HashMap ();]
[ for(Map.Entry day: days.entrySet()) {]
Indeed, I’m a big fan of Java 8 foreach method! Great article, your are doing great… Keep it up