Syntax
stream.reduce(identity, accumulator)Examples
reduce(): Combining Elements
Reducing a stream down to a single accumulated value.
import java.util.List;
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 15
int product = numbers.stream()
.reduce(1, (a, b) -> a * b);
System.out.println(product); // 120count(), anyMatch(), allMatch()
Common checks that return a single boolean or number.
import java.util.List;
List<Integer> numbers = List.of(2, 4, 6, 8, 10);
long count = numbers.stream().filter(n -> n > 5).count();
System.out.println(count); // 3
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
System.out.println(allEven); // true
boolean anyOverTen = numbers.stream().anyMatch(n -> n > 10);
System.out.println(anyOverTen); // falseNumeric Streams: sum, average, max
IntStream and its relatives provide direct numeric aggregation methods.
import java.util.List;
List<Integer> scores = List.of(85, 92, 78, 90, 88);
int total = scores.stream().mapToInt(Integer::intValue).sum();
System.out.println(total); // 433
double average = scores.stream().mapToInt(Integer::intValue).average().orElse(0);
System.out.println(average); // 86.6
int highest = scores.stream().mapToInt(Integer::intValue).max().orElse(0);
System.out.println(highest); // 92findFirst() and findAny()
Retrieving a single matching element from a stream, wrapped in an Optional.
import java.util.List;
import java.util.Optional;
List<String> names = List.of("Fola", "Zain", "Jamal", "Zoe");
Optional<String> firstZ = names.stream()
.filter(name -> name.startsWith("Z"))
.findFirst();
firstZ.ifPresent(name -> System.out.println("Found: " + name)); // Found: ZainBest practices
- Use reduce() for custom aggregation logic, but prefer built-in terminal operations (sum(), count(), max()) when they already do what you need
- Use anyMatch()/allMatch()/noneMatch() instead of manually looping and setting a boolean flag - they short-circuit and stop as soon as the result is known
- Use mapToInt()/mapToDouble() to switch to a primitive numeric stream before calling sum()/average(), since those are not available on a generic Stream<Integer>
- Handle the Optional returned by findFirst(), max(), and similar methods explicitly - never assume a matching element exists
At a glance
- Purpose
- General-purpose application development
- File extension
- .java
- Runs in
- Java Virtual Machine
- Usually used with
- JDK and Java libraries
Specifications & further reading
Related Java documentation
Lambda Expressions
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value. Lambdas work with functional interfaces (interfaces with exactly one abstract method), letting you replace a full anonymous class implementation with a short, focused expression. Lambdas are the foundation that makes Java's Stream API and functional-style programming possible.Stream Basics (map, filter, forEach)
The Stream API, introduced in Java 8, provides a functional, declarative way to process sequences of elements from collections, arrays, or other sources. A stream pipeline consists of a source, zero or more intermediate operations (like filter and map, which are lazy and return a new stream), and exactly one terminal operation (like forEach or collect) that actually triggers processing.Collectors
Collectors, used with the stream terminal operation collect(), provide ready-made ways to accumulate stream elements into a final result - a List, Set, Map, a joined String, or grouped/partitioned data. The java.util.stream.Collectors class offers factory methods like toList(), joining(), groupingBy(), and counting() that cover the vast majority of real-world aggregation needs.Optional
Optional<T> is a container object that may or may not hold a non-null value, designed to make the possibility of 'no result' explicit in a method's return type, reducing NullPointerExceptions. Rather than returning null and hoping callers remember to check for it, a method returning Optional<T> signals clearly that a value might be absent, and provides safe methods like isPresent(), ifPresent(), and orElse() for handling both cases.
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value. Lambdas work with functional interfaces (interfaces with exactly one abstract method), letting you replace a full anonymous class implementation with a short, focused expression. Lambdas are the foundation that makes Java's Stream API and functional-style programming possible.Stream Basics (map, filter, forEach)
The Stream API, introduced in Java 8, provides a functional, declarative way to process sequences of elements from collections, arrays, or other sources. A stream pipeline consists of a source, zero or more intermediate operations (like filter and map, which are lazy and return a new stream), and exactly one terminal operation (like forEach or collect) that actually triggers processing.Collectors
Collectors, used with the stream terminal operation collect(), provide ready-made ways to accumulate stream elements into a final result - a List, Set, Map, a joined String, or grouped/partitioned data. The java.util.stream.Collectors class offers factory methods like toList(), joining(), groupingBy(), and counting() that cover the vast majority of real-world aggregation needs.Optional
Optional<T> is a container object that may or may not hold a non-null value, designed to make the possibility of 'no result' explicit in a method's return type, reducing NullPointerExceptions. Rather than returning null and hoping callers remember to check for it, a method returning Optional<T> signals clearly that a value might be absent, and provides safe methods like isPresent(), ifPresent(), and orElse() for handling both cases.