Reputation: 469
Apologies if the title is not very clear.
I have a list of Employee objects and I want to create a map such that the department (a string attribute inside the Employee object) is the key, and the set of employees as the value. I'm able to achieve it by doing this
Map<String, Set<Employee>> employeesGroupedByDepartment =
employees.stream().collect(
Collectors.groupingBy(
Employee::getDepartment,Collectors.toCollection(HashSet::new)
)
);
Now, how can I make my key (department) to be in uppercase? I couldn't find a way to uppercase the output of the method reference Employee::getDepartment!
Note: Unfortunately, I can neither change the getDepartment method to return the value in uppercase nor can I add a new method (getDepartmentInUpperCase) to the Employee object.
Upvotes: 3
Views: 97
Reputation: 6123
It's probably easier to do it using a normal lambda:
Map<String, Set<Employee>> employeesGroupedByDepartment =
employees.stream().collect(
Collectors.groupingBy(
e -> e.getDepartment().toUpperCase(), Collectors.toCollection(HashSet::new)
)
);
If you really want to use method references instead, there are ways to chain method references (but I wouldn't bother with them). Probably something like:
Map<String, Set<Employee>> employeesGroupedByDepartment =
employees.stream().collect(
Collectors.groupingBy(
((Function<Employee,String>)Employee:getDepartment).andThen(String::toUpperCase)),Collectors.toCollection(HashSet::new)
)
);
Upvotes: 6