Common Intermediate Operations: filter, map, flatMap
You'll learn the three most essential intermediate operations that transform and filter stream elements without executing the pipeline.
The Big Three Intermediate Operations
While streams support many intermediate operations, three stand out as fundamental building blocks: filter(), map(), and flatMap(). These operations let you transform data declaratively, building up a pipeline that won't execute until a terminal operation triggers it.
filter(): Selecting Elements
filter() accepts a Predicate and keeps only elements that match the condition. Think of it like a bouncer at a club—only items that pass the test get through.
It transforms a stream of n elements into a stream of ≤n elements (potentially fewer, never more).
map(): Transforming Elements One-to-One
map() applies a Function to each element, transforming it into something else. Every input element produces exactly one output element—it's a one-to-one transformation.
Think of it like a factory assembly line where each item gets modified but the count stays the same. You might map String to Integer (their lengths), or Person to String (their names).
flatMap(): Flattening Nested Structures
flatMap() applies a function that returns a stream for each element, then flattens all those streams into one. It's a one-to-many transformation that "flattens" the results.
Imagine unpacking boxes: each box (element) contains multiple items (a stream), and flatMap() unpacks everything into a single collection. Perfect for dealing with nested collections or splitting strings into words.
Why They're Intermediate
Remember: these operations are lazy. Calling them builds the pipeline but processes nothing until you add a terminal operation like forEach() or collect().
Key Takeaway: filter() selects elements, map() transforms one-to-one, and flatMap() transforms one-to-many with flattening—all three are lazy intermediate operations that only execute when a terminal operation triggers the pipeline.