The map Operation: Function-Based Transformation
What you'll learn: How map transforms each element in a stream by applying a function, creating a one-to-one mapping from input to output.
The Core Idea
The map operation is one of the most fundamental stream transformations. It takes each element in your stream and applies a function to it, producing a new stream where every input element has been transformed into exactly one output element. Think of it like a factory assembly line: each item goes in, gets modified, and comes out the other side—one input becomes one output.
Unlike filter, which may remove elements, map always preserves the stream's size. If you have 10 elements in your stream, you'll have 10 elements after mapping—they'll just be transformed versions.
How map Works
The map operation accepts a Function<T, R> as its parameter:
- T is the type of elements in the input stream
- R is the type of elements in the resulting stream
Stream<String> names = Stream.of("alice", "bob", "charlie");
Stream<String> upperNames = names.map(String::toUpperCase);
// Result: "ALICE", "BOB", "CHARLIE"
Here, map applied toUpperCase to each string, producing a new stream of uppercase strings.
Type Transformation
Unlike filter, map can change the element type:
Stream<String> words = Stream.of("cat", "elephant", "ox");
Stream<Integer> lengths = words.map(String::length);
// Result: 3, 8, 2
We transformed String elements into Integer elements representing their lengths.
Key Takeaway: The map operation performs a one-to-one transformation on stream elements using a function, preserving stream size while potentially changing element types.