Reduce

Reduction combines many elements into one result. A product starts with an identity value of one and folds each number into the running result.

A correct identity must leave any value unchanged when combined with it. That property matters when a reduction is split for parallel work.

Fold values into one result

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> dimensions = List.of(2, 3, 4);
        int volume = dimensions.stream()
                .reduce(1, (product, size) -> product * size);
        System.out.println(volume);
    }
}

Output:

24

The accumulator receives the current product and the next dimension until one volume remains.

Use specialized operations such as mapToInt(...).sum() when they state a calculation more plainly. reduce is useful for custom combinations such as this product.

Use zero as the identity and add each cost to the running total.