A reduction identity must leave any value unchanged under the accumulator, and the accumulator must be associative for parallel reduction.
Java Stream.reduce: identity and associative accumulator contracts
Use the operation's real identity
For integer addition the identity is zero. Starting at one appears to add a single fee in a sequential pass, but a parallel reduction can apply that identity in multiple partitions. Add the fee after the reduction instead. For multiplication the identity is one.
The example sums invoice amounts and adds a fixed handling fee exactly once. It uses long arithmetic to reduce overflow risk, but a long can still overflow; a financial ledger should define bounds or use a decimal representation. Overflow contracts apply before choosing a reduction shape.
Avoid order-sensitive arithmetic
Subtraction and floating-point addition are not generally associative in the way parallel reduce expects. Floating-point rounding can change with grouping. If a stable money total matters, use integer minor units with overflow checks or BigDecimal under a defined scale policy.
Working program
import java.util.Arrays;
public class InvoiceAmountReduction {
public static void main(String[] args) {
long amountCents = Arrays.asList(4700L, 1250L, 800L)
.parallelStream().reduce(0L, Long::sum);
long handlingFeeCents = 275L;
System.out.println("amountCents=" + amountCents);
System.out.println("withFeeCents=" + Math.addExact(amountCents, handlingFeeCents));
}
}Output
amountCents=6750
withFeeCents=7025Cost and ownership
Summation is O(n) work and O(p) partial results for p parallel tasks, apart from the input list. Parallel scheduling overhead can exceed the useful work for small inputs. Math.addExact checks the final fee addition; check each intermediate addition too when overflow is possible.
Common Mistakes
- Do not use one as the identity for addition.
- Do not use subtraction as a parallel reduction accumulator.
- Do not assume long or floating-point totals are safe for every financial input.
Read next
Java checked integer arithmetic: reject overflow before updating state, Java parallel streams: forEach and forEachOrdered have different order contracts, Java streams: lazy pipelines and bounded results, Java Collectors.toMap: choose a duplicate-key rule.
