Java 如何进行函数组合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19834611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do function composition?
提问by Yuriy Nakonechnyy
While rather impatiently waiting for Java 8 release and after reading brilliant 'State of the Lambda' article from Brian GoetzI noticed that function compositionwas 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 中实现这一点?
采纳答案by Andrey Chaschev
There is a default interface function Function::andThen
and Function::compose
:
有一个默认的接口函数Function::andThen
和Function::compose
:
Function<Person, String> toCountry = personToAddress.andThen(addressToCountry);
回答by Mikhail Golubtsov
There is one flaw in using compose
and andThen
. You have to have explicit variables, so you can't use method references like this:
使用compose
and有一个缺陷andThen
。你必须有显式变量,所以你不能像这样使用方法引用:
(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)