Careeroza
Terminal Operations and reduce
Terminal Operations
| Operation | Returns |
|---|---|
toList() (Java 16), collect(...) | a collection / map / string |
forEach, forEachOrdered | nothing (side effect) |
count(), min, max | long / Optional |
anyMatch, allMatch, noneMatch | boolean (short-circuit) |
findFirst, findAny | Optional |
reduce | combined single value |
toArray | array |
reduce
reduce(identity, accumulator) combines all elements into one value. The identity is the starting value (0 for sum, 1 for product, "" for concatenation). Without an identity, reduce returns an Optional because the stream could be empty.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(4, 8, 15, 16, 23, 42);
int sum = nums.stream().reduce(0, Integer::sum);
int product = nums.stream().limit(3).reduce(1, (a, b) -> a * b);
Optional<Integer> max = nums.stream().reduce(Integer::max);
Optional<Integer> none = List.<Integer>of().stream().reduce(Integer::sum);
System.out.println("sum = " + sum);
System.out.println("product of first 3 = " + product);
System.out.println("max = " + max.orElseThrow());
System.out.println("empty reduce = " + none);
System.out.println("count > 10: " + nums.stream().filter(n -> n > 10).count());
System.out.println("any even? " + nums.stream().anyMatch(n -> n % 2 == 0));
System.out.println("all < 50? " + nums.stream().allMatch(n -> n < 50));
System.out.println("min = " + nums.stream().min(Integer::compare).get());
}
}Output
sum = 108 product of first 3 = 480 max = 42 empty reduce = Optional.empty count > 10: 4 any even? true all < 50? true min = 4
Stream Reuse Error
Example
A stream can be consumed only once.
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Stream<String> s = Stream.of("a", "b");
System.out.println(s.count());
System.out.println(s.count());
}
}Output
2 Exception: java.lang.IllegalStateException: stream has already been operated upon or closed