Java Stream forEach() Example

In this tutorial, we will learn Java 8 Stream forEach() terminal operation with an example.

The Java Stream forEach() method is a terminal operation that starts the internal iteration of the elements in the Stream and applies a Consumer (java.util.function.Consumer) to each element in the Stream. The forEach() method returns void. 

Java Stream forEach() Example

Here is a Java Stream forEach() example:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("one");

        Stream<String> stream = stringList.stream();

        stream.forEach( element -> { System.out.println(element); });
    }
}

Output:

one
two
three
one

Java Stream Methods/APIs Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments