以一个例子来介绍如何使用lambda,我们来实现一个加减乘除,通过一个接口方法来实现。
首先来创建一个接口。
interface Calculator{ public void test(T t); }
接下来建立一个类来放计算的两个数。
//X Y即泛型 class Num{ X x; Y y; public Num(X x, Y y) { this.x = x; this.y = y; } }
下面我就直接用lambda来写
public class Test {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
check(new Num(4, 5),(num)-> System.out.println((Integer) num.x+(Integer) num.y));
check(new Num(4, 5),(num)-> System.out.println((Integer) num.x*(Integer) num.y));
check(new Num(4, 5),(num)-> System.out.println((Integer) num.x-(Integer) num.y));
check(new Num(4, 5),(num)-> System.out.println((Integer) num.x/(Integer) num.y));
}
public static void check(Num num,Calculator cal){
cal.test(num);
}
}
当然还有另外一种写法就是直接调Num里的静态方法
check(new Num(4, 5),Num::sub); class Num{ X x; Y y; public Num(X x, Y y) { this.x = x; this.y = y; } public static void sub(Num num){ System.out.println((Integer) num.x+(Integer) num.y); } }



