Learn to Transform Grouped Elements with mapping
You'll learn how to use Collectors.mapping() to transform elements after grouping or partitioning them, enabling more flexible collection pipelines.
What Is mapping as a Downstream Collector?
When you group or partition data, you often want to transform the elements within each group before collecting them. That's where mapping comes in—it's a collector that wraps another collector, applying a transformation function to each element first.
Think of it like a two-step assembly line: first, items are sorted into bins (grouping/partitioning), then within each bin, items are transformed before final packaging (mapping + collecting).
The Syntax
Collectors.mapping(Function<T, U> mapper, Collector<U, A, R> downstream)
- mapper: transforms each element
- downstream: collects the transformed elements (like
toList(),toSet(),counting(), etc.)
Practical Example
Say you have a list of people and want to group them by age, but collect only their names (not the whole Person object):
Map<Integer, List<String>> namesByAge = people.stream()
.collect(groupingBy(
Person::getAge,
mapping(Person::getName, toList())
));
Without mapping, you'd get Map<Integer, List<Person>>. With mapping, you extract just the names and collect those into lists per age group.
Why Not Just Use map() Before Grouping?
Because mapping works inside each group. If you map() before groupingBy, you'd lose the original object needed for classification.
Key Takeaway: Collectors.mapping() lets you transform elements within each group or partition, combining classification with selective data extraction in a single, elegant pipeline.