All topics
library
intermediate

Java Streams: Intermediate vs Terminal Operations

Distinguish lazy intermediate operations from eager terminal operations and understand stream pipeline evaluation.

Java Streams (Java 8) have two types of operations:

Intermediate operations = setting up an assembly line (adding stations). Terminal operation = pressing the 'Start' button. Nothing moves until Start is pressed. Short-circuiting = the conveyor belt stops when the output bin is full.

Key Concepts

1
Intermediate (lazy): return a new Stream, not executed until a terminal operation is called. - filter(Predicate): select elements matching a condition - map(Function): transform each element - flatMap(Function): one-to-many transform (flatten) - sorted(): sort (requires seeing all elements) - distinct(): remove duplicates - peek(Consumer): observe elements (for debugging) - limit(n): take first n elements (short-circuiting) - skip(n): skip first n elements
2
Terminal (eager): trigger pipeline execution and produce a result. - collect(Collector): accumulate into a collection (toList, toMap, groupingBy) - forEach(Consumer): iterate (void) - reduce(BinaryOperator): combine elements into one value - count(): count elements - findFirst(), findAny(): short-circuiting - anyMatch(), allMatch(), noneMatch(): short-circuiting boolean - toArray(): convert to array - min(), max(): find extremes
3
Key properties: - Streams are single-use: after a terminal operation, the stream is consumed - Lazy evaluation: intermediate operations build a pipeline, terminal triggers it - Short-circuiting: limit(), findFirst(), anyMatch() stop early - Streams don't modify the source collection