Java Stream forEach() Example

1. Introduction

Java Streams provide a modern approach to iterating over collections and arrays with powerful operations like forEach(). This method allows developers to execute a specific action on each element of a stream, making it a staple for processing collections efficiently and concisely. The forEach() method is particularly useful for executing side-effects such as printing out elements or storing results in a non-stream result container. In this tutorial, we will explore how to utilize the forEach() method in Java Streams, providing insights into its practical applications and benefits.

Key Points

1. forEach() is a terminal operation that consumes the stream to apply a given action to each element.

2. It is typically used for its side-effect capabilities, such as modifying an external variable or interacting with external services.

3. Unlike other terminal operations, forEach() does not return a result, making it ideal for operations that don't require a resultant collection or value but need to enact changes or perform actions.

2. Program Steps

1. Import the necessary Java utilities.

2. Create a collection of elements.

3. Convert the collection into a stream.

4. Apply the forEach() method to perform an action on each element.

5. Print results to demonstrate the side effects.

3. Code Program

import java.util.Arrays;
import java.util.List;

public class StreamForEachExample {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Diana");

        // Step 3: Convert the list to a stream
        System.out.println("Names in the list:");

        // Step 4: Apply forEach to print each element
        names.stream().forEach(name -> System.out.println(name));
    }
}

Output:

Names in the list:
Alice
Bob
Charlie
Diana

Explanation:

1. A List of String is created containing several names. This list serves as the source for the stream.

2. names.stream() converts the list into a stream, allowing stream operations to be performed on its elements.

3. The forEach() method is applied with a lambda expression name -> System.out.println(name), which specifies the action to be taken on each element. Here, it prints each name to the console.

4. The output demonstrates that each element of the stream is accessed and processed individually. The forEach() operation ensures that every element in the original list is outputted to the console, showcasing its utility in applying functions to elements of a stream sequentially.

5. This example highlights how forEach() can be used to interact directly with each element of a stream without altering the stream's content, making it ideal for logging, debugging, or other operations that require access to individual elements without transformation.


Comments