Skip to content

Reductions & Totals

The Course
•
20 min study

A reduction combines a sequence into one result. You used mapToInt and sum in intermediate; now define a reduction for a type that has no primitive sum operation. A good reduction has an identity, a combining operation and a clear empty-input result.

Understand the contract

For exact decimal addition, zero is the identity: adding it changes no numerical value. BigDecimal.add is the combining operation. reduce(identity, accumulator) starts from that identity and combines each element. The method reference BigDecimal::add is equivalent to (left, right) -> left.add(right).

Use an identity appropriate to the representation you promise. Starting from new BigDecimal("0.00") gives an empty monetary report two decimal places. This example's inputs are nonnull values already normalized to at most two places. No rounding occurs during the sum. The source list stays unchanged because BigDecimal is immutable.

Addition is associative numerically: regrouping additions preserves the value. Subtraction is not an appropriate replacement when you expect a sum or regrouping invariance. Streams are not automatically faster than loops, and parallel execution is outside this browser course. Learn the mathematical contract first; a compact pipeline does not make a bad accumulator correct.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.math.BigDecimal;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<BigDecimal> amounts = List.of(new BigDecimal("1.20"), new BigDecimal("2.30"));
        BigDecimal total = amounts.stream().reduce(new BigDecimal("0.00"), BigDecimal::add);
        System.out.println(total.toPlainString());
        System.out.println(List.<BigDecimal>of().stream().reduce(new BigDecimal("0.00"), BigDecimal::add));
    }
}
Check your prediction
Text
3.50
0.00

Trace a different case

List.<BigDecimal>of() explicitly supplies the type argument to the generic of method when creating an empty list. You can instead declare a List<BigDecimal> variable and call List.of() on the right. Explicit type arguments are occasionally useful when a chain gives inference too little context.

The equivalent loop below makes state changes visible. The accumulator variable is reassigned, but none of the individual amount objects is mutated. This is a useful reference implementation for testing a pipeline; keep it simple enough to inspect independently.

Compare the boundary case Java
import java.math.BigDecimal;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<BigDecimal> amounts = List.of(new BigDecimal("1.20"), new BigDecimal("2.30"));
        BigDecimal total = new BigDecimal("0.00");
        for (BigDecimal amount : amounts) {
            total = total.add(amount);
        }
        System.out.println(total);
        System.out.println(amounts);
    }
}
Check your prediction
Text
3.50
[1.20, 2.30]

Check the identity and one contribution separately

A reduction has two independent opportunities to be wrong: the starting identity and the combination. Empty input isolates the identity. A one-item input checks whether combining with the identity preserves that item's value. Two unequal contributions check that later values accumulate rather than replace earlier ones.

For decimal totals, use 0.00 as the report's representation policy and exact addition as the combination. For a different operation, do not copy zero automatically: a product would need another identity. State the empty-input meaning before choosing an overload.

Keep a short loop as an independent reference in tests. A stream and loop should agree on the same contract, including selection and ownership. Testing only a plausible printed total can miss a source mutation or a lost contribution.

Build it yourself

Exercise

Reductions & Totals: practice

Write totalAtLeast(List<BigDecimal>, BigDecimal minimum) to sum values numerically greater than or equal to minimum. Inputs and elements are nonnull two-place nonnegative values. On [1.20, 2.30, 2.00] with minimum 2.00 print 4.30; on empty input print 0.00. Preserve input and do not round individual additions.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Compare numerical amounts with compareTo, select matching entries, then reduce with an exact identity.

Hint 2: a first step

The inclusive boundary requires compareTo(minimum) >= 0, not equals(minimum).

Show one solution
Java
import java.math.BigDecimal;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<BigDecimal> amounts = List.of(new BigDecimal("1.20"), new BigDecimal("2.30"), new BigDecimal("2.00"));
        System.out.println(totalAtLeast(amounts, new BigDecimal("2.00")));
        System.out.println(totalAtLeast(List.of(), new BigDecimal("2.00")));
    }

    static BigDecimal totalAtLeast(List<BigDecimal> amounts, BigDecimal minimum) {
        return amounts.stream()
            .filter(amount -> amount.compareTo(minimum) >= 0)
            .reduce(new BigDecimal("0.00"), BigDecimal::add);
    }
}

Expected output:

Text
4.30
0.00

The filter uses compareTo(minimum) >= 0, so 2.00 is included: the boundary case is why the answer is 4.30 and not 2.30. The reduction starts at new BigDecimal("0.00"), which both handles the empty list and keeps the result's scale at two. Nothing is rounded during the sum, so no error builds up across additions, and the stream never modifies the source list.

Change it and test again

Test a threshold below every amount, above every amount, and exactly equal to one amount. Write the loop version and compare numerical results. Change the identity to 1.00: even empty input now reveals a defect. Change the filter to strict greater-than: the exact-boundary case must fail.

Explain before moving on

Which result belongs to empty input? Why does reducing with a fake first amount complicate that case? Explain why a total is a derived value rather than a mutable field you must manually keep synchronized with the collection.

Was this article helpful?

Your response is saved on this device.