[英]How to do function composition?
While rather impatiently waiting for Java 8 release and after reading brilliant 'State of the Lambda' article from Brian Goetz I noticed that function composition was not covered at all.在相当不耐烦地等待 Java 8 发布并阅读了 Brian Goetz 的精彩“Lambda 状态”文章后,我注意到函数组合根本没有被涵盖。
As per above article, in Java 8 the following should be possible:根据上面的文章,在 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;
Now if I would like to compose these two functions to have a function mapping Person
to country, how can I achieve this in Java 8?现在,如果我想将这两个函数组合成一个将
Person
映射到国家的函数,我如何在 Java 8 中实现这一点?
有default
接口函数Function::andThen
和Function::compose
:
Function<Person, String> toCountry = personToAddress.andThen(addressToCountry);
There is one flaw in using compose
and andThen
.使用
compose
和andThen
有一个缺陷。 You have to have explicit variables, so you can't use method references like this:你必须有显式变量,所以你不能像这样使用方法引用:
(Person::getAddress).andThen(Address::getCountry)
It won't be compiled.它不会被编译。 What a pity!
太遗憾了!
But you can define an utility function and use it happily:但是你可以定义一个效用函数并愉快地使用它:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.