Mapping filtering and reduction
What you will learn
Mapping transforms elements, filtering selects them, and reduction combines them into a single answer. Choose a primitive stream when numeric operations make the result clearer; choose flatMap when each input contributes zero or more values.
- Choose map, filter or flatMap based on the output shape.
- Compute reductions with a valid identity.
- Handle empty numeric aggregates and integer overflow deliberately.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Select and total inventory
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { record Item(String name, int units) {} var items = List.of(new Item("pen", 4), new Item("book", 0), new Item("clip", 9)); System.out.println(items.stream().filter(i -> i.units() > 0).map(Item::name).toList()); System.out.println(items.stream().mapToInt(Item::units).sum()); }}Expected output:
[pen, clip]13The first pipeline returns names; the second sums primitive quantities.
Transform one item or expand many
map returns one result per input. filter retains inputs satisfying a predicate. flatMap consumes the streams produced by a mapper as a single flattened stream; a batch with no elements contributes nothing. mapToInt, mapToLong and mapToDouble select primitive representations for numerical aggregation. boxed changes a primitive stream into its wrapper-object counterpart.
Reduction and empty inputs
For reduce(identity, operator), the identity must leave a value unchanged under the operator: zero for addition, one for multiplication. The operator must be associative, so grouping the calculations differently does not alter the result. Subtraction is not associative. reduce(operator) returns an Optional because there is no value to return from an empty source. Primitive streams offer sum, min, max and average; average is absent for an empty stream. summaryStatistics() reports count, sum, min, max and average in one pass; check count before using extrema. For empty IntSummaryStatistics, min is Integer.MAX_VALUE and max is Integer.MIN_VALUE, not actual observed values.
Choose clear numerical contracts
Integer arithmetic can overflow. An IntStream sum returns int; for totals that may exceed int, widen before adding with mapToLong or asLongStream. Even long has finite capacity. Floating-point addition may vary with grouping. Do not promise exact parallel floating-point equality. Use a loop when state changes, multiple exits or domain rules are clearer imperatively.
Flatten shipments
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var shipments = List.of(List.of("A", "B"), List.<String>of(), List.of("C")); System.out.println(shipments.stream().flatMap(List::stream).toList()); }}Expected output:
[A, B, C]Each inner list becomes a stream; an empty shipment contributes no item.
Reduce and handle absence
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { System.out.println(Stream.of(2, 3, 4).reduce(1, (a, b) -> a * b)); System.out.println(Stream.<Integer>empty().reduce(1, (a, b) -> a * b)); System.out.println(IntStream.empty().average().orElse(-1)); }}Expected output:
241-1.0One is the multiplication identity. The fallback -1 denotes no average for this nonnegative dataset.
One-pass statistics and wider totals
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var s = IntStream.of(4, 2, 9).summaryStatistics(); System.out.println(s.getCount() + ":" + s.getSum() + ":" + s.getMin() + ":" + s.getMax()); System.out.println(IntStream.of(Integer.MAX_VALUE, 1).asLongStream().sum()); }}Expected output:
3:15:2:92147483648The statistics summarize the three values; conversion to long happens before the large addition.
Common mistakes
A mutable list is not a suitable shared identity for reduce. Use collect for mutable accumulation. Avoid replacing a missing maximum with zero when negative values are valid: that would invent a value.
Practice
Flatten batches [3, 0, 2], [], [4, -1]. Retain strictly positive values and print their total as a long and their count using two fresh pipelines.
Expected output:
93Compare your answer with the manual practice criteria.
Official reading: Java SE 25 Stream API · Stream package contracts · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mapping filtering and reduction — knowledge check
Original Java stream contract and boundary questions. Java 21-compatible scope.
Which operation turns a stream of lists into a stream of their items?
What identity fits integer multiplication?
What does IntStream.empty().average() contain?
Why convert to long before summing large int values?
Which reduction operation is associative for ordinary integer addition without exact-overflow exceptions?