在方法引用返回的对象上调用方法

cdo*_*doe 3 java-8

如果标题不是很清楚,请道歉.

我有一个Employee对象列表,我想创建一个映射,使得部门(Employee对象中的字符串属性)是键,而员工集合作为值.通过这样做,我能够实现它

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            Employee::getDepartment,Collectors.toCollection(HashSet::new)
        )
    );
Run Code Online (Sandbox Code Playgroud)

现在,我怎样才能使我的密钥(部门)成为大写?我找不到方法来大写方法引用Employee :: getDepartment的输出!

注意:不幸的是,我既不能更改getDepartment方法以返回大写的值,也不能将新方法(getDepartmentInUpperCase)添加到Employee对象.

Dod*_*ion 6

使用普通的lambda可能更容易:

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            e -> e.getDepartment().toUpperCase(), Collectors.toCollection(HashSet::new)
        )
    );
Run Code Online (Sandbox Code Playgroud)

如果你真的想要使用方法引用,有方法链接方法引用(但我不打扰它们).可能是这样的:

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            ((Function<Employee,String>)Employee:getDepartment).andThen(String::toUpperCase)),Collectors.toCollection(HashSet::new)
        )
    );
Run Code Online (Sandbox Code Playgroud)