Basic map Examples: Primitive Transformations
What You'll Learn
You'll see how to use the map operation to perform simple transformations on stream elements, like converting strings to uppercase or numbers to their squares.
Understanding Basic Transformations
The map operation takes each element in a stream and applies a function to transform it into something else. Think of it like a factory assembly line: each item goes in, gets modified according to your instructions, and comes out transformed.
For primitive transformations, you're typically doing straightforward conversions—changing one value to another through a simple operation.
Common Transformation Examples
Strings to Uppercase
List<String> names = List.of("alice", "bob", "charlie");
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Result: ["ALICE", "BOB", "CHARLIE"]
Numbers to Their Squares
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
// Result: [1, 4, 9, 16, 25]
String Lengths
List<String> words = List.of("cat", "elephant", "dog");
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
// Result: [3, 8, 3]
Simple Type Conversions
List<Integer> numbers = List.of(10, 20, 30);
List<String> strings = numbers.stream()
.map(String::valueOf)
.collect(Collectors.toList());
// Result: ["10", "20", "30"]
Notice how map changes the type of stream elements when needed—from String to Integer, or vice versa. The transformation function defines both what happens to each element and what type comes out.
Key Takeaway: The map operation transforms each stream element using a function, making it perfect for simple conversions like uppercase transformation, mathematical operations, or type changes—each input becomes exactly one output.