Mapping Values Within Groups
What you'll learn: How to transform elements after grouping them, so each group contains modified values instead of the original objects.
The Core Idea
When you use groupingBy(), the resulting map contains the original elements as values. But what if you want each group to hold something derived from those elements—like just their names, IDs, or calculated scores? That's where Collectors.mapping() comes in as a downstream collector.
Think of it like sorting mail into bins by zip code (grouping), but instead of keeping entire envelopes in each bin, you extract just the letters inside (mapping). You're transforming what gets stored in each group.
How It Works
The mapping() collector takes two arguments:
- A mapping function that transforms each element
- Another downstream collector that gathers the transformed values
Map<String, List<String>> result = people.stream()
.collect(Collectors.groupingBy(
Person::getCity,
Collectors.mapping(Person::getName, Collectors.toList())
));
Here, we group Person objects by city, but each city's list contains only the names (strings), not the full Person objects.
Why This Matters
Without mapping(), you'd get Map<String, List<Person>>. With it, you get Map<String, List<String>> directly—cleaner and more memory-efficient when you don't need the full objects.
You can chain mapping() with any downstream collector: toSet() for unique values, joining() for comma-separated strings, or even another mapping() for multiple transformations.
Key Takeaway: Use Collectors.mapping() as a downstream collector to extract or transform specific parts of elements within each group, giving you precise control over what each group's values look like.