目前BiFunction
接口(interface)有两个方法andThen()
和apply()
。我在网络上找到了不同的示例,但下面的示例是我无法弄清楚的-“这些方法的链接如何工作”
示例 1:
BiFunction<String, String,String> bi = (x, y) -> {
return x + y;
};
Function<String,String> f = x-> x+" spinner";
System.out.println(bi.andThen(f).apply("hello", " world"));
阅读以下链接后'Default andThen() method in BiFunction interface ',我采取了以下几行
Assume we had two functions f and g , function f doing some logic and function g doing some other type of logic so when you compose f.andThen(g) that essentially means g(f(x)) i.e. we first apply the function given as argument f(x) and then apply the function g to the result.
得出的结论是 bi.apply("hello", "world"))
首先发生,然后 结果
是
传递给bi.andThen(f(result))
,这给出了最终输出hello world spinner
。
我理解了一些,但并不完全满意。我不得不问这个问题,因为过去我使用过构建器模式,如下所示,
BankAccount account = new BankAccount.Builder("bank_account")
.withOwner("account_owner")
.atBranch("branch_name")
.openingBalance(balance)
.build();
这里,方法调用按顺序发生,首先初始化 Builder
(静态)类,然后 withOwner
分配所有者名称并返回构建器,然后分配分支名称并返回构建器,
给出下一个期初余额并返回构建器,最后构建将返回 BankAccount 实例。请参阅 BankAccount
类。
public class BankAccount {
public static class Builder {
private long accountNumber;
private String owner;
private String branch;
private double balance;
public Builder(long accountNumber) {
this.accountNumber = accountNumber;
}
public Builder withOwner(String owner){
this.owner = owner;
return this;
}
public Builder atBranch(String branch){
this.branch = branch;
return this;
}
public Builder openingBalance(double balance){
this.balance = balance;
return this;
}
public BankAccount build(){
//Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
BankAccount account = new BankAccount(); //Since the builder is in the BankAccount class, we can invoke its private constructor.
account.accountNumber = this.accountNumber;
account.owner = this.owner;
account.branch = this.branch;
account.balance = this.balance;
return account;
}
}
}
正如您所看到的,这些方法是按顺序调用的,方法的输出 -withOwner
、atBranch
、openingBalance
是链中的 Builder
实例。对我来说,这称为方法链接,因为每个方法的输出按顺序用于稍后,这非常清楚。但是,我的问题是 - 上述示例 1 的方法链接(BiFunction 及其方法链接)
如何在内部工作。
最佳答案
您可以查看默认实现:
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
如您所见,它们首先调用 BiFunction
的 apply
方法(即,它们计算 apply(t, u)
),然后将该方法的结果传递给 Function
的 apply
方法 (after.apply(...)
)。
我不确定为什么您觉得 andThen
没有按顺序调用这些方法。毕竟,bi.andThen(f)
创建了一个 BiFunction
,它首先调用 bi
的 apply
方法,然后调用 f
的 apply
方法(正如名称 andThen
所暗示的那样)。
关于Java 8 : How BiFunction works while using andThen() and apply() methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56421502/