Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
java 8
foreach

Java 8 forEach

Educative Answers Team

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)); 
    }
}

RELATED TAGS

java
java 8
foreach
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring