Java 8 forEach

Share

The Java 8 forEach is an enhanced form of the standard for loop. It was first introduced in Java 5.

Java 8 provides the updated forEach() method with the ability to iterate the elements of a collection. The Iterable and Stream interface includ​es collection classes that extend the Iterable interface – the forEach loop can be used with such interfaces.

svg viewer

Syntax

Have a look at the signature of the Java 8 forEach loop below:

svg viewer

Code

The code snippet below illustrates the usage of the Java 8 forEach loop:

import java.util.ArrayList;
import java.util.List;
class ForEachDemo {
public static void main( String args[] ) {
List<String> Fruits = new ArrayList<String>();
Fruits.add("Apple");
Fruits.add("Banana");
Fruits.add("Kiwi");
Fruits.add("Lemon");
// using forEach to print out the list using
// lambda expression
Fruits.forEach(fruit -> System.out.println(fruit));
}
}
Copyright ©2024 Educative, Inc. All rights reserved