Java Stream forEach() Example

1. Introduction

This tutorial demonstrates how to use the forEach() method of the Java Stream API. forEach() is a terminal operation that helps in iterating over each element of the stream, allowing actions to be performed on each element. This method simplifies operations on collections and is a key part of functional programming in Java.

Key Points

1. forEach() is used for iterating over each element of a stream to execute a provided action.

2. It is a terminal operation, which means it consumes the stream and you cannot use the stream after forEach() is called.

3. forEach() should be used for operations that do not affect the underlying data source (non-interfering).

2. Program Steps

1. Create a Stream of elements.

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

3. Demonstrate actions like printing elements or performing calculations.

3. Code Program

import java.util.stream.Stream;

public class StreamForEachExample {

    public static void main(String[] args) {
        // Stream of elements
        Stream<String> fruitStream = Stream.of("apple", "banana", "cherry", "date", "elderberry");

        // Apply forEach to print each element
        fruitStream.forEach(fruit -> System.out.println("Fruit: " + fruit));

        // Stream of numbers for a sum calculation
        Stream<Integer> numberStream = Stream.of(1, 2, 3, 4, 5);

        // Mutable container for the sum
        final int[] sum = {0};

        // Apply forEach to calculate sum of elements
        numberStream.forEach(number -> sum[0] += number);
        System.out.println("Sum of numbers: " + sum[0]);
    }
}

Output:

Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date
Fruit: elderberry
Sum of numbers: 15

Explanation:

1. Stream.of("apple", "banana", "cherry", "date", "elderberry") creates a stream of fruit names.

2. fruitStream.forEach(fruit -> System.out.println("Fruit: " + fruit)) iterates over each fruit in the stream and prints its name.

3. Stream.of(1, 2, 3, 4, 5) creates a stream of numbers.

4. The sum of the numbers is calculated using a forEach loop, where each element is added to a sum accumulator (sum[0] += number).

5. The use of an array sum to store the accumulator value is a workaround to allow modification of the variable within the lambda expression.

Comments