gpt4 book ai didi

java - 函数合成怎么做?

转载 作者:IT老高 更新时间:2023-10-28 21:00:01 27 4
gpt4 key购买 nike

在相当不耐烦地等待 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 映射到国家/地区的函数,我该如何在 Java 8 中实现呢?

最佳答案

default接口(interface)函数Function::andThenFunction::compose:

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

关于java - 函数合成怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com