Collectors Reducing Custom Fold

Fold stream elements with Collectors.reducing in its identity, mapped, and Optional forms, including an empty-stream fallback.

JavaData Integrity

Code

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

public class Main {
    record Order(String customer, int items, double total) {
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order("ada", 3, 42.0),
                new Order("bob", 1, 9.5),
                new Order("cy", 5, 71.25));

        // reducing performs a custom fold over every element
        int items = orders.stream()
                .collect(Collectors.reducing(0, Order::items, Integer::sum));
        System.out.println("items: " + items);

        // the identity form folds values that are already extracted
        double revenue = orders.stream()
                .map(Order::total)
                .collect(Collectors.reducing(0.0, Double::sum));
        System.out.println("revenue: " + revenue);

        // the identity becomes the result when the stream is empty
        String empty = orders.stream()
                .filter(order -> order.items() > 100)
                .map(Order::customer)
                .collect(Collectors.reducing("none", (left, right) -> left + "," + right));
        System.out.println("fallback: " + empty);

        System.out.println("largest: " + orders.stream()
                .collect(Collectors.reducing((a, b) -> a.total() > b.total() ? a : b)));
    }
}

How it works

Collectors Reducing Custom Fold comes down to the classes Main and Order and the function main.

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

Points of care

  • Runs with what the toolchain already gives you — nothing extra.

Putting it to use

Entry signature: public static void main(String[] args)

Look for the items:, revenue:, fallback: prefixes when the file runs; they tie each line to its step.

Core lines

.collect(Collectors.reducing("none", (left, right) -> left + "," + right));
.collect(Collectors.reducing(0, Order::items, Integer::sum));
.collect(Collectors.reducing(0.0, Double::sum));

Interactive Tools for This Topic

FAQ

What does Collectors Reducing Custom Fold print when run?
Run it as a complete program — the output lines carry labels such as `items:`, `revenue:`, `fallback:`.