Extracting Object Properties with map
What You'll Learn
You'll learn how to use the map operation to pull out specific fields from objects in a stream, transforming a stream of complex objects into a stream of their individual properties like names, IDs, or other attributes.
The Core Idea
Think of map as a spotlight that focuses on just one aspect of each object. When you have a stream of complex objects (like Person, Product, or Employee), you often don't need the whole object—just one property from each. The map operation extracts that property, creating a new stream of just those values.
This is one of the most common real-world uses of map: transforming a Stream<ComplexObject> into a Stream<SimpleProperty>.
How It Works
The pattern is simple:
stream.map(object -> object.getProperty())
or with a method reference:
stream.map(ComplexObject::getProperty)
Practical Examples
Extracting names from Person objects:
Stream<Person> people = Stream.of(
new Person("Alice", 25),
new Person("Bob", 30)
);
Stream<String> names = people.map(Person::getName);
// Stream contains: "Alice", "Bob"
Extracting IDs from Product objects:
Stream<Product> products = getProducts();
Stream<Integer> ids = products.map(Product::getId);
Multiple extractions in a pipeline:
products.stream()
.map(Product::getName) // Extract names
.map(String::toUpperCase) // Transform them
.forEach(System.out::println);
Key Takeaway: Use map to extract specific properties from objects, transforming a stream of complex objects into a stream of single attributes—this is the foundation of focused data processing in streams.