Collectors, Grouping, and Reduction
Collectors turn streams into lists, sets, maps, grouped structures, and summaries.
Map<Integer, List<String>> byLength =
names.stream()
.collect(Collectors.groupingBy(String::length));
int totalLength =
names.stream()
.mapToInt(String::length)
.sum();
groupingBy is useful for classification. partitioningBy splits values into two groups. Reduction operations combine elements into a result.
Prefer built-in collectors when they express the operation clearly. Custom collectors require careful supplier, accumulator, combiner, and finisher design.
Key Takeaways
- Use
groupingByfor classification and aggregation. - Primitive streams can reduce boxing for numeric operations.
- Custom collectors must account for sequential and parallel semantics.