lambda表达式无法指定类型参数,因此它不是泛型的。但是,与lambda表达式相关联的函数接口是泛型的。在这种情况下,lambda表达式的目标类型由声明函数接口引用时指定的参数类型确定。
interface SomeFunc {
T func(T t);
}interface MyGeneric<T> {
T compute(T t);
}
public class LambdaGenericFuncInterfaceTest {
public static void main(String args[]) {
MyGeneric<String> reverse = (str) -> { // Lambda Expression
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);
return result;
};
MyGeneric<Integer> factorial = (Integer n) -> { // Lambda Expression
int result = 1;
for(int i=1; i <= n; i++)
result = i * result;
return result;
};
System.out.println(reverse.compute("Lambda Generic Functional Interface"));
System.out.println(factorial.compute(7));
}
}输出结果
ecafretnI lanoitcnuF cireneG adbmaL 5040