Java Stream forEach()

In this guide, you will learn about the Stream forEach() method in Java programming and how to use it with an example.

1. Stream forEach() Method Overview

Definition:

The Stream.forEach() method is a terminal operation that performs an action for each element in the stream. It is used for iterating over the stream elements, much like a for-each loop over a collection.

Syntax:

void forEach(Consumer<? super T> action)

Parameters:

- action: A Consumer functional interface, which specifies the action to be performed on each stream element.

Key Points:

- The forEach() method does not return a result (returns void).

- It is a terminal operation, so it closes the stream after its execution.

- The order in which the elements are processed is not guaranteed for parallel streams.

- While forEach() is useful for side effects (like printing), it's not always the best choice for modifying the underlying data source.

- It should be used carefully with parallel streams to avoid thread-safety issues.

2. Stream forEach() Method Example

import java.util.stream.Stream;

public class StreamForEachExample {
    public static void main(String[] args) {
        Stream<String> fruitsStream = Stream.of("Apple", "Banana", "Cherry", "Date", "Elderberry");

        // Using forEach to print each element in the stream
        fruitsStream.forEach(fruit -> System.out.println("Fruit: " + fruit));
    }
}

Output:

Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit: Elderberry

Explanation:

In the provided example, we have a stream of fruit names. We employ the forEach() method to iterate over each fruit in the stream and print it. This illustrates how the forEach() method can be used for side effects like printing each element of a stream.

3. Stream forEach() Method - Real-World Example

import java.util.ArrayList;
import java.util.List;

class Order {
    private final String orderId;
    private final double amount;

    public Order(String orderId, double amount) {
        this.orderId = orderId;
        this.amount = amount;
    }

    public String getOrderId() {
        return orderId;
    }

    public double getAmount() {
        return amount;
    }
}

public class OrderProcessing {
    public static void main(String[] args) {
        List<Order> orders = new ArrayList<>();
        orders.add(new Order("A123", 250.50));
        orders.add(new Order("B456", 150.00));
        orders.add(new Order("C789", 100.25));

        orders.stream()
              .forEach(order -> System.out.println("Order ID: " + order.getOrderId() + ", Amount: " + order.getAmount()));
    }
}

Output:

Order ID: A123, Amount: 250.5
Order ID: B456, Amount: 150.0
Order ID: C789, Amount: 100.25

Explanation:

In this example, we have a class Order representing an order, and we have a list of Order objects. We use the forEach() method to print out the orderId and amount of each order.

Comments