Reputation: 323
I'm trying to work out why the following code fails to compile:
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))));
Can't all Functions be cahined in java 8?
Upvotes: 2
Views: 8152
Reputation: 121048
Exactly, andThen
is applied to the result from that Function
, for example:
Function<Employee, String> chained = getFirstName.andThen(x -> x.toUpperCase());
x -> x.toUpperCase()
(or this can be replaced with a method reference String::toUpperCase
) is applied to the String
result from getFirstName
Function.
How do you imagine chaining them? One Function
returns String
, so that makes it impossible to chain. But you can return both those fields via a single 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;
};
Upvotes: 6