Stream Pipeline: Intermediate vs Terminal Operations
1Concept
A Stream pipeline consists of: 1. Source (Collection, Array, I/O channel); 2. Intermediate Operations (filter, map, flatMap, sorted, distinct) which are LAZY and return a new Stream without executing; 3. Terminal Operation (collect, forEach, reduce, count) which is EAGER and triggers traversal.
2Architecture Diagram
[ Source Collection ]
|
v (Lazy Intermediate)
[ .filter(p -> p.active) ]
|
v (Lazy Intermediate)
[ .map(User::getEmail) ]
|
v (Eager Terminal Operation)
[ .collect(Collectors.toList()) ] ---> Triggers full pipeline execution!3Code Example
Core Java
import java.util.List;
import java.util.stream.Collectors;
public class StreamPipelineDemo {
record Order(int id, double amount, String status) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order(101, 250.0, "COMPLETED"),
new Order(102, 45.0, "PENDING"),
new Order(103, 1200.0, "COMPLETED"),
new Order(104, 310.0, "COMPLETED")
);
// Fluent Stream Pipeline
List<Integer> highValueOrderIds = orders.stream()
.filter(o -> "COMPLETED".equals(o.status())) // Intermediate
.filter(o -> o.amount() > 200.0) // Intermediate
.map(Order::id) // Intermediate
.collect(Collectors.toList()); // Terminal execution
System.out.println("High-Value Completed Order IDs: " + highValueOrderIds);
}
}4Expected Output
High-Value Completed Order IDs: [101, 103, 104]
5Key Takeaways
- ✓Streams are single-use; attempting to reuse a consumed stream throws `IllegalStateException`.
- ✓Intermediate operations execute only when a terminal operation is invoked (Lazy Evaluation).
- ✓Short-circuit terminal operations (`findFirst()`, `anyMatch()`) terminate processing early.