Stream Processing and Pipelines

Shows how to process collections using Java Streams with map, filter, reduce, and collect operations to transform and aggregate data efficiently.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamProcessing {
    record Product(String name, String category, double price) {}

    public static void main(String[] args) {
        List<Product> products = List.of(
            new Product("Laptop", "Electronics", 1200.0),
            new Product("Phone", "Electronics", 800.0),
            new Product("Desk", "Furniture", 300.0),
            new Product("Chair", "Furniture", 150.0)
        );

        double totalElectronics = products.stream()
            .filter(p -> p.category().equals("Electronics"))
            .mapToDouble(Product::price)
            .sum();

        Map<String, List<Product>> byCategory = products.stream()
            .collect(Collectors.groupingBy(Product::category));

        Map<String, Double> avgPriceByCategory = products.stream()
            .collect(Collectors.groupingBy(
                Product::category,
                Collectors.averagingDouble(Product::price)
            ));

        System.out.println("Total Electronics: $" + totalElectronics);
        System.out.println("Grouped: " + byCategory.keySet());
        System.out.println("Avg prices: " + avgPriceByCategory);
    }
}

How the snippet works

The moving parts are the classes StreamProcessing and Product and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Using it

Running the file prints labeled results such as Total Electronics: $, Grouped:, Avg prices: — each operation’s effect is visible in the output.

Key statements

.collect(Collectors.groupingBy(Product::category));
.collect(Collectors.groupingBy(
Product::category,
Collectors.averagingDouble(Product::price)
));
.filter(p -> p.category().equals("Electronics"))
.mapToDouble(Product::price)
.sum();

FAQ

What does Stream Processing and Pipelines print when run?
No setup needed: run the file and look for labeled lines like `Total Electronics: $`, `Grouped:`, `Avg prices:` in the output.