在相当不耐烦地等待Java8发布的时候,在阅读了brilliant 'State of the Lambda' article from Brian Goetz之后,我注意到function composition根本没有被涉及到。
根据上面的文章,在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;现在,如果我想将这两个函数组合成一个将Person映射到country的函数,我如何在Java8中实现这一点?
发布于 2013-11-07 21:44:37
default接口函数有Function::andThen和Function::compose
Function<Person, String> toCountry = personToAddress.andThen(addressToCountry);发布于 2015-09-29 16:09:14
使用compose和andThen有一个缺陷。你必须有显式的变量,所以你不能像这样使用方法引用:
(Person::getAddress).andThen(Address::getCountry)它不会被编译。太遗憾了!
但是您可以定义一个实用函数并愉快地使用它:
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)https://stackoverflow.com/questions/19834611
复制相似问题