怎么做功能组合?

时间:2013-11-07 11:20:45

标签: java java-8

虽然不耐烦地等待Java 8发布并且在阅读了精彩的'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,我怎样才能在Java 8中实现这个功能?

2 个答案:

答案 0 :(得分:51)

默认界面功能Function::andThenFunction::compose

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

答案 1 :(得分:16)

使用composeandThen存在一个缺陷。你必须有显式变量,所以你不能使用这样的方法引用:

(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)