如果标题不是很清楚,请见谅。
我有一个 Employee 对象列表,我想创建一个映射,这样 department(Employee 对象中的字符串属性)是键,员工集是值。我可以通过这样做来实现它
Map<String, Set<Employee>> employeesGroupedByDepartment =
employees.stream().collect(
Collectors.groupingBy(
Employee::getDepartment,Collectors.toCollection(HashSet::new)
)
);
现在,我怎样才能让我的键(部门)变成大写呢?我找不到将方法引用 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<String, Set<Employee>> employeesGroupedByDepartment =
employees.stream().collect(
Collectors.groupingBy(
((Function<Employee,String>)Employee:getDepartment).andThen(String::toUpperCase)),Collectors.toCollection(HashSet::new)
)
);
关于java-8 - 对方法引用返回的对象调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163834/