java8引入了lambda语法,和python中匿名函数一样,可以进行函数式的编程,简化了很多工作。
具体语法就是
参数 -> 方法体
其中参数中的 括号()是可选的,参数类型也是可选的,方法体中的大{}也是可选的,返回关键字return也是可选的
下面用一个详细的例子来说明:
package java8;
//先定义一个接口,只能有一个方法,a和b就是要参与计算的值
public interface MathOperation {
int operation(int a,int b);
}
然后在这个接口上进行方法体的扩展
package java8;
//定义了一个具体的计算规则
public class ImpMathOperation {
//a,b都是普通的参数,mathOperation指定了具体的运算逻辑
public int operate(int a,int b,MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
public static void main(String args[]) {
ImpMathOperation t = new ImpMathOperation();
//以下的动作就相当在实现接口的同时也指定了具体的方法逻辑。
//普通的加满乘除
MathOperation add = (a,b) -> a+b;
MathOperation sub = (int a,int b) -> a-b;
MathOperation mul = (int a,int b) -> a*b;
MathOperation div = (int a,int b) -> {return a/b;};
//定义特殊的逻辑计算
MathOperation type1 = (int a,int b) -> (a+b)*a;
MathOperation type2 = (int a,int b) -> (a+100)*(b-30);
System.out.println(t.operate(1, 2, add));
System.out.println(t.operate(3, 4, sub));
System.out.println(t.operate(1, 2, mul));
System.out.println(t.operate(3, 4, div));
System.out.println(t.operate(3, 4, type1));
System.out.println(t.operate(3, 4, type2));
}
}