ewa*_*all 3 java generic-collections guava
我正在使用Guava集合的转换函数,并发现自己制作了许多像这样的伪代码的匿名函数:
Function<T, R> TransformFunction = new Function<T, R>() {
public R apply(T obj) {
// do what you need to get R out of T
return R;
}
};
Run Code Online (Sandbox Code Playgroud)
...但是由于我需要重用其中的一些,我想把频繁的那些放到一个类中以便于访问.
我很尴尬地说(因为我不太使用Java),我无法弄清楚如何使类方法返回这样的函数.你能?
我想你想要做的是创建一个可以在整个代码中重用的公共静态函数.
例如:
public static final Function<Integer, Integer> doubleFunction = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input * 2;
}
};
Run Code Online (Sandbox Code Playgroud)
或者如果你想冷静并使用lambdas
public static final Function<Integer, Integer> doubleFunction = input -> input * 2;
Run Code Online (Sandbox Code Playgroud)