Java 8 对方法引用返回的对象调用方法

Java 8 对方法引用返回的对象调用方法,java-8,Java 8,如果标题不太清楚,请道歉 我有一个Employee对象列表,我想创建一个映射,使department(Employee对象中的字符串属性)成为键,Employee集作为值。我可以通过这样做来实现它 Map<String, Set<Employee>> employeesGroupedByDepartment = employees.stream().collect( Collectors.groupingBy( Emplo

如果标题不太清楚,请道歉

我有一个Employee对象列表,我想创建一个映射,使department(Employee对象中的字符串属性)成为键,Employee集作为值。我可以通过这样做来实现它

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            Employee::getDepartment,Collectors.toCollection(HashSet::new)
        )
    );
Map employeesGroupedByDepartment=
employees.stream().collect(
收集者分组(
Employee::getDepartment,Collectors.toCollection(HashSet::new)
)
);
现在,如何使我的钥匙(部门)为大写?我找不到将方法reference Employee::getDepartment的输出大写的方法


注意:很遗憾,我既不能更改getDepartment方法以返回大写值,也不能向Employee对象添加新方法(getDepartmentInUpperCase)。

使用普通lambda可能更容易:

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            e -> e.getDepartment().toUpperCase(), Collectors.toCollection(HashSet::new)
        )
    );
Map employeesGroupedByDepartment=
employees.stream().collect(
收集者分组(
e->e.getDepartment().toUpperCase(),Collectors.toCollection(HashSet::new)
)
);
如果您真的想使用方法引用,那么有一些方法可以链接方法引用(但我不想麻烦它们)。可能是这样的:

Map<String, Set<Employee>> employeesGroupedByDepartment = 
    employees.stream().collect(
        Collectors.groupingBy(
            ((Function<Employee,String>)Employee:getDepartment).andThen(String::toUpperCase)),Collectors.toCollection(HashSet::new)
        )
    );
Map employeesGroupedByDepartment=
employees.stream().collect(
收集者分组(
((函数)Employee:getDepartment)。然后(String::toUpperCase)),collector.toCollection(HashSet::new)
)
);

…顺便说一句,除非要求集合为
HashSet
collector.toCollection(HashSet::new)
可以替换为
collector.toSet()