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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:34:55  来源:igfitidea点击:

How to do function composition?

javajava-8

提问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 Personto country, how can I achieve this in Java 8?

现在,如果我想将这两个函数组合成一个映射Person到国家/地区的函数,我如何在 Java 8 中实现这一点?

采纳答案by Andrey Chaschev

There is a default interface function Function::andThenand Function::compose:

有一个默认的接口函数Function::andThenFunction::compose

Function<Person, String> toCountry = personToAddress.andThen(addressToCountry);

回答by Mikhail Golubtsov

There is one flaw in using composeand andThen. You have to have explicit variables, so you can't use method references like this:

使用composeand有一个缺陷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)