虽然不耐烦地等待Java 8发布,在阅读Brian Goetz的精彩"Lambda状态"文章之后,我注意到功能组合根本没有被覆盖.
根据上面的文章,在Java 8中应该可以:
// having classes Address and Person
public class Address {
private String country;
public String getCountry() {
return country;
}
}
public class Person {
private Address address;
public Address getAddress() {
return address;
}
}
// we should be able to reference their methods like
Function<Person, Address> personToAddress = Person::getAddress;
Function<Address, String> addressToCountry = Address::getCountry;
Run Code Online (Sandbox Code Playgroud)
现在,如果我想将这两个函数组合成一个函数映射Person到country,我怎样才能在Java 8中实现这一点?
And*_*hev 52
有一个默认的接口函数Function::andThen和Function::compose:
Function<Person, String> toCountry = personToAddress.andThen(addressToCountry);
Run Code Online (Sandbox Code Playgroud)
Mik*_*sov 17
使用compose和存在一个缺陷andThen.你必须有显式变量,所以你不能使用这样的方法引用:
(Person::getAddress).andThen(Address::getCountry)
Run Code Online (Sandbox Code Playgroud)
它不会被编译.太遗憾了!
但是你可以定义一个实用程序函数并愉快地使用它:
public static <A, B, C> Function<A, C> compose(Function<A, B> f1, Function<B, C> f2) {
return f1.andThen(f2);
}
compose(Person::getAddress, Address::getCountry)
Run Code Online (Sandbox Code Playgroud)