Advanced level · Module 1: Generics, Lambdas and Streams · Lesson 3 of 4
Stream Pipelines
Process collections with streams: filter, map, sort, reduce and collect, and know when a loop is clearer.
In this lesson you will
- Build stream pipelines with intermediate and terminal operations
- Use reduce, sum and collect to produce results
Key concepts
stream sourceintermediate operation (filter, map, sorted)terminal operation (collect, sum, count)laziness
The lesson
A stream pipeline has a source, zero or more intermediate operations and one terminal operation: sales.stream().filter(s -> s.amount() > 10000).map(Sale::item).distinct().sorted().toList(). Nothing runs until the terminal operation, and a stream can be used only once.
mapToInt or mapToDouble produce primitive streams with sum(), average() and max(). reduce combines elements step by step, and collect gathers results into lists, sets, maps or strings, for example Collectors.joining(", ").
Streams shine for filter–transform–summarise tasks. For logic with many early exits or complex state, a plain loop can be clearer. Keep lambdas inside streams free of side effects such as adding to an external list.
Step by step
- Filter a list of sales to one region.
- Map to amounts and sum them with mapToInt.
- Produce a sorted list of distinct item names.
- Join the names into one comma-separated string.
Practice activity
Rewrite three loop-based report methods as stream pipelines and confirm with existing unit tests that results are unchanged.
Expected result: All tests still pass, and each report method is a short, readable pipeline.
Check your understanding
-
When does a stream pipeline actually run?
Show answer
When a terminal operation such as collect or sum is called.
-
Can the same stream object be used twice?
Show answer
No; a stream can be consumed only once.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.