Lambda旨在为单方法接口提供内联实现代码,并能够像常规变量一样传递它们。我们称它们为功能接口。
例如,在匿名类中编写Runnable并启动Thread看起来像:
//旧方法
new Thread(
new Runnable(){
public void run(){
System.out.println("运行逻辑...");
}
}
).start();
//来自Java 8的lambda
new Thread(
()-> System.out.println("运行逻辑...")
).start();现在,与上述一致,假设您有一些自定义接口:
interface TwoArgInterface {
int operate(int a, int b);
}您如何使用lambda在代码中实现此接口的实现?与上面显示的Runnable示例相同。请参阅下面的驱动程序:
public class CustomLambda {
public static void main(String[] args) {
TwoArgInterface plusOperation = (a, b) -> a + b;
TwoArgInterface divideOperation = (a,b)->{
if (b==0) throw new IllegalArgumentException("Divisor can not be 0");
return a/b;
};
System.out.println("3和5的加号运算为: " + plusOperation.operate(3, 5));
System.out.println("将运算50除以25为: " + divideOperation.operate(50, 25));
}
}