- groupingBy operation on Collectors provides a way to aggregate the result of a stream operation into a map, where the map contains items whose keys are the groupings.
- There are two implementations, the first implementation performs on-stage grouping, the second performs two-stage grouping (grouping and reduction)
stream of employees
Stream<Employee> employees = Stream.of(
new Employee("Joe", "Blogs", "Sales", 100.0),
new Employee("Richardo", "Banks", "Engineering", 50.0),
new Employee("Hewlet", "Packer", "Warehouse", 40.0),
new Employee("Shelly", "Cooper", "Warehouse", 40.0)
);
another stream of employees
Stream<Employee> employees_2 = Stream.of(
new Employee("Joe", "Blogs", "Sales", 100.0),
new Employee("Richardo", "Banks", "Engineering", 50.0),
new Employee("Hewlet", "Packer", "Sales", 140.0)
);
USAGE
collecting stream in a Map using one-stage grouping
Map<String, List<Employee>> employeeGroup = employees
.collect(Collectors.groupingBy(employee -> employee.getDepartment()));
collecting stream in a Map using two-stage grouping and reduction
Map<String, Double> employeeGroup_reduced = employees_2.collect(
Collectors.groupingBy(employee -> employee.getDepartment(), Collectors.summingDouble(employee -> employee.getSalary())
)
);
Comments
Post a comment