java.util.function中的Function,Supplier,Predicate和其他函数式接口广泛应用在支持lambda表达式的API中。
在此简单介绍Function接口
Fuction接口的主要方法有:
R apply(T t) : 将对象对应到输入参数上并返回计算结果
default<V> Function<T,V> : 将两个fuction整合,然后返回一个能执行两个Function对象功能的Function对象
除apply还有以下接口:
default <V> Function<T,V> andThen(Function<? super R,? extends V> after) 返回一个先执行当前函数对象apply方法再执行after函数对象apply方法的函数对象。
default <V> Function<T,V> compose(Function<? super V,? extends T> before)返回一个先执行before函数对象apply方法再执行当前函数对象apply方法的函数对象。
static <T> Function<T,T> identity() 返回一个执行了apply()方法之后只会返回输入参数的函数对象。
下面是一个简单的使用范例:
public static void testFunction(int basic, Function<Integer, Integer> function) {
int value = function.apply(basic);
System.out.print(value + "\n");
}
public static void main(String... args) {
testFunction(1, val -> val + 1000);
testFunction(5, val -> val * 100);
}
输出:1001
500