Mapping to Different Types
What You'll Learn
You'll learn how to use the map operation to transform stream elements from one data type into a completely different type, such as converting strings into integers or extracting properties from objects.
The Core Idea
So far, you've seen map transform elements while keeping the same type (like doubling integers). But map's real power shines when you need to change the type entirely. The map operation takes a Function<T, R> where T is your input type and R is your output type—they can be different!
Think of it like a factory assembly line: raw materials (one type) go in, and finished products (a different type) come out.
Common Type Transformations
String to Integer:
Stream<String> numbers = Stream.of("10", "20", "30");
Stream<Integer> integers = numbers.map(Integer::parseInt);
Object to Property:
Stream<Person> people = Stream.of(new Person("Alice", 30), new Person("Bob", 25));
Stream<String> names = people.map(Person::getName);
Stream<Integer> ages = people.map(Person::getAge);
Converting to String:
Stream<Integer> numbers = Stream.of(1, 2, 3);
Stream<String> strings = numbers.map(String::valueOf);
// or
Stream<String> strings2 = numbers.map(n -> "Number: " + n);
Why This Matters
Type transformation is essential when your data source provides one type, but your processing logic needs another. You might read strings from a file but need numeric calculations, or have complex objects but only need specific fields downstream.
Key Takeaway: The map operation transforms not just values but types—it takes a Stream<T> and produces a Stream<R>, allowing you to reshape your data pipeline to match each processing stage's needs.