如何进行函数组合? [英] How to do function composition?

查看:23
本文介绍了如何进行函数组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然相当不耐烦地等待 Java 8 发布并阅读了精彩的'状态来自 Brian Goetz 的 Lambda 文章 我注意到函数组合根本没有被涵盖.

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 中应该可以:

As per above article, in Java 8 the following should be possible:

// 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 映射到国家的函数,我如何在 Java 8 中实现这一点?

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?

推荐答案

default接口函数Function::andThenFunction::compose:

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

这篇关于如何进行函数组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆