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 includes collection classes that extend the Iterable interface – the forEach
loop can be used with such interfaces.
Have a look at the signature of the Java 8 forEach
loop below:
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)); } }
RELATED TAGS
View all Courses