看起来很简单,但我没有找到如何在单个对象上应用函数形式 guava api 的解释
例如我有以下功能
Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return (int) Math.pow(input, 2);
}
};
我想将其应用到
整数 i = 6;
我该怎么做
与谓词相同,我如何对单个对象进行谓词
最佳答案
只需调用Function.apply
即可。
final int applied = powerOfTwo.apply(i);
一个Function
is simply an interface
定义一个方法:
T apply(F input)
您的 powerOfTwo
只是一个 anonymous class
实现函数
接口(interface)
。
对于谓词
也是如此。
请注意,在 Java 8 中,有一个 whole host of Function
types使用 lambda 表达式,您的代码将变为:
Function<Integer, Integer> powerOfTwo = i -> i * i;
或者,使用 int
版本(这样您就不会自动装箱为 Integer
):
IntFunction powerOfTwo = i -> i * i;
你问我也可以链式吗?。 Java 7 中的答案是:不会。由于 Guava Function
interface
仅定义了一种方法,因此它无法提供该功能。您需要使用 Functions
实用程序类为 compose
多种功能:
Function<Integer, Integer> composed = Functions.compose(powerOfTwo, powerOfTwo);
对于 Java 8,由于 default method Function
接口(interface)实际上可以提供大量功能,同时仍然只有一个 abstract
方法。因此在 Java 8 中你可以这样做:
Function<Integer, Integer> composed = powerOfTwo.compose(powerOfTwo);
或者甚至:
Function<Integer, Integer> composed = powerOfTwo.compose(i -> i + 2);
关于java - 函数 Guava 在单个对象上应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020057/