Java
Module 6: Collectors & Data Aggregation
By Utility Zone · 2026-01-27T18:46:44.37542
Target Audience
- Java developers using Streams in real applications
- Developers working with reporting and aggregation logic
- Anyone preparing for Java 8 interviews or backend work
1. Objective of This Module
By the end of this module, you will:
- Understand what Collectors are
- Convert Streams into different data structures
- Perform grouping, partitioning, and aggregation
- Build real-world reporting logic using Java 8
2. What Is a Collector?
A Collector:
- Is a terminal operation
- Accumulates Stream elements into a result
- Is commonly used with
collect()
List<String> result =
list.stream().collect(Collectors.toList());
3. Common Collectors
toList()
List<String> names =
employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());
toSet()
Set<String> uniqueDepartments =
employees.stream()
.map(Employee::getDepartment)
.collect(Collectors.toSet());
toMap()
Map<Integer, String> employeeMap =
employees.stream()
.collect(Collectors.toMap(
Employee::getId,
Employee::getName
));
⚠️ Keys must be unique unless a merge function is provided.
4. groupingBy()
Used to group elements based on a condition.
Map<String, List<Employee>> byDepartment =
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
groupingBy with Downstream Collector
Map<String, Long> countByDepartment =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()
));
5. partitioningBy()
Used when the condition results in true / false.
Map<Boolean, List<Employee>> partitioned =
employees.stream()
.collect(Collectors.partitioningBy(
e -> e.getSalary() > 50000
));
6. Joining Strings
String names =
employees.stream()
.map(Employee::getName)
.collect(Collectors.joining(", "));
7. Summarizing and Averaging
IntSummaryStatistics stats =
employees.stream()
.collect(Collectors.summarizingInt(Employee::getSalary));
Provides:
- count
- sum
- min
- max
- average
8. Real-World Use Cases
- Reports by department
- User statistics dashboards
- Sales summaries
- Analytics data preparation
9. Common Mistakes
- Overusing grouping when simple mapping is enough
- Creating complex collectors hurting readability
- Forgetting merge functions in
toMap()
10. Hands-On Exercises
Exercise 1
Group employees by department.
Exercise 2
Partition employees by active / inactive.
Exercise 3
Create a summary report of salaries.
11. Summary
- Collectors turn Streams into results
- groupingBy and partitioningBy are powerful tools
- Downstream collectors unlock advanced aggregation
12. What’s Next?
➡️ Module 7: Optional & Null Safety