import java.util.*;
import java.util.stream.*;
class Demo {
void example() {
var nums = List.of(1, 2, 3, 4, 5);
// With identity — never returns Optional
int sum = nums.stream().reduce(0, Integer::sum);
int product = nums.stream().reduce(1, (a, b) -> a * b);
int max = nums.stream().reduce(Integer.MIN_VALUE, Integer::max);
System.out.printf("sum=%d product=%d max=%d%n", sum, product, max);
// Without identity — returns Optional (empty stream → empty)
Optional<Integer> maybeMax = nums.stream().reduce(Integer::max);
maybeMax.ifPresent(System.out::println);
// Three-arg parallel reduce — identity, accumulator, combiner
int parallelSum = nums.parallelStream()
.reduce(0, Integer::sum, Integer::sum);
System.out.println(parallelSum);
// String concat — but prefer Collectors.joining for this
String joined = List.of("a", "b", "c").stream()
.reduce("", (acc, s) -> acc + s);
System.out.println(joined); // abc
}
}
Create a free account and build your private vault. Share publicly whenever you want.