我正在尝试找出以下代码无法编译的原因:
Function<Employee, String> getLastName = (Employee employee) -> {
return employee.getName().substring(employee.getName().indexOf(" ") + 1);
};
Function<Employee, String> getFirstName = (Employee employee) -> {
return employee.getName().substring(0, employee.getName().indexOf(" "));
};
Function chained = getFirstName.apply(employees.get(2).andThen(getFirstName.apply(employees.get(2))));
不是所有的函数都可以缓存在 java 8 中吗?
最佳答案
确切地说,andThen
应用于该Function
的结果,例如:
Function<Employee, String> chained = getFirstName.andThen(x -> x.toUpperCase());
x -> x.toUpperCase()
(或者这可以替换为方法引用 String::toUpperCase
)应用于 String
来自 getFirstName
函数的结果。
您如何想象将它们链接在一起?一个 Function
返回 String
,因此无法链接。 但是您可以通过单个Function
返回这两个字段:
Function<Employee, String[]> bothFunction = (Employee employee) -> {
String[] both = new String[2];
both[0] = employee.getName().substring(employee.getName().indexOf(" ") + 1);
both[1] = employee.getName().substring(0, employee.getName().indexOf(" "));
return both;
};
关于function - Java函数链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803254/