Intermediate 8 min
Lambdas and stream pipelines
A stream pipeline expresses work on a sequence as a chain of small operations.
How it works
A filter describes which items continue to the next step. The following map receives only those items. The terminal operation collects the result when you ask for it. Keep each lambda small so you can explain that transformation independently.
Walk through an example
Filter keeps the items that pass a condition. Map changes each kept item. A terminal operation such as sum or collect asks for the result.
What to watch for
A stream is used once. Avoid modifying external state inside stream operations, especially if the pipeline may run in parallel.
Code example
public class Main {
public static void main(String[] args) {
var result = java.util.List.of(2, 3, 4, 5).stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.toList();
System.out.println(result);
}
}Check your understanding
What values appear in the resulting list?
See the example and explanation
- Worked example
- Given
[2, 3, 4, 5], keep even values, then double them - Answer
[4, 8]
Filtering keeps 2 and 4. Mapping doubles each, preserving their encounter order in this pipeline.