背景:
没有系统学习过Java,第一次在公司代码里看到很多不明所以的Lambda使用方法,最后在官网教程上找到答案。不得不说,网上Java的中文资料太多鱼目混珠,甚至还有些无脑复制粘贴,污染互联网环境,但退一步想,是不是百度这个搜索引擎对内容的去重做得太粗糙呢...
正文:
将只含有一个抽象函数的接口称为functional interface(可以有多个default或者static函数,只对抽象函数的个数进行限制)。
当function interface作为参数时,可以用lambda表达式简化,而不是特地写一个类去实现接口或者使用匿名类。
show me the code:
public class Calculator {
// 只有一个抽象函数的interface(接口内缺省的函数是public abstract)
interface IntegerMath {
int operation(int a, int b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator myApp = new Calculator();
// 创建接口的引用addition
IntegerMath addition = (a, b) -> a + b;
// 创建接口的引用subtraction
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " +
myApp.operateBinary(40, 2, addition));
System.out.println("20 - 10 = " +
myApp.operateBinary(20, 10, subtraction));
}
}