我试图找出以下代码无法编译的原因:
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))));
Run Code Online (Sandbox Code Playgroud)
不能在java 8中包含所有函数吗?
确切地说,andThen应用于结果Function,例如:
Function<Employee, String> chained = getFirstName.andThen(x -> x.toUpperCase());
Run Code Online (Sandbox Code Playgroud)
x -> x.toUpperCase()(或者可以用方法参考替换String::toUpperCase)应用于Function 的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;
};
Run Code Online (Sandbox Code Playgroud)