Java 25 (LTS) reference · Stream API
Java Stream reduce() Method
Combine all elements into one value with an accumulator function, starting from an identity value.
Java 25 (LTS) Since Java 8
Syntax
stream.reduce(identity, accumulator)
Parameters
| Parameter | Description |
|---|---|
identityT |
The starting value (0 for sums, 1 for products). |
accumulatorBinaryOperator<T> |
Combines a running result with the next element. |
Return value
The combined value.
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4);
System.out.println(nums.stream().reduce(0, Integer::sum));
System.out.println(nums.stream().reduce(1, (a, b) -> a * b));
}
}
Output
10 24
Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Optional<String> longest = Stream.of("tea", "kettle", "mug").reduce((a, b) -> a.length() >= b.length() ? a : b);
System.out.println(longest.orElse("none"));
}
}
Output
kettle
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.mapToInt()· Map to an IntStream of primitive ints, which has sum(), average(), min(), max() and summaryStatistics().stream.count()· Return the number of elements in the stream (a long). A terminal operation.- Java Streams · tutorial