玩转Lambda表达式,⾃定义lambda接⼝编程
- ⾃定义lambda接⼝流程
定义⼀个函数式接⼝ 需要标注此接⼝ @FunctionalInterface,否则万⼀团队成员在接⼝上加了其他⽅法则容易出故障编写⼀个⽅法,输⼊需要操做的数据和接⼝在调⽤⽅法时传⼊数据 和 lambda 表达式,⽤来操作数据。
- 需求,定义⼀个可以使⽤加减乘除的接⼝ 以前需要定义4个⽅法
使⽤Lambda表达式后
@FunctionalInterface
public interface OperFunction<R,T> {
R operator(T t1, T t2);
}
public static void main(String[] args) throws Exception {
System.out.println(operator(20, 5, (Integer x, Integer y) -> {
return x * y;
}));
System.out.println(operator(20, 5, (x, y) -> x + y));
System.out.println(operator(20, 5, (x, y) -> x - y));
System.out.println(operator(20, 5, (x, y) -> x / y));
}
public static Integer operator(Integer x, Integer y,
OperFunction<Integer, Integer> of) {
return of.operator(x, y);
}