Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a method on the object returned by method reference

Tags:

java-8

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.

like image 978
cdoe Avatar asked Jun 30 '26 18:06

cdoe


1 Answers

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)
        )
    );
like image 195
DodgyCodeException Avatar answered Jul 04 '26 12:07

DodgyCodeException