Java 8: Sum and aggregate with Stream.reduce

reduce folds a stream into a single value using an identity and an accumulator.

Code
List<Integer> nums = List.of(2, 4, 6, 8);
int sum = nums.stream().reduce(0, Integer::sum);
int product = nums.stream().reduce(1, (a, b) -> a * b);
System.out.println("sum=" + sum + " product=" + product);
Output
sum=20 product=384
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26