定义⼀个函数式接⼝ 需要标注此接⼝ @FunctionalInterface,否则万⼀团队成员在接⼝上加了其他⽅法则容易出故障
编写⼀个⽅法,输⼊需要操做的数据和接⼝
在调⽤⽅法时传⼊数据 和 lambda 表达式,⽤来操作数据
# 自定义接口
@FunctionalInterface
public interface OperFunction<R,T> {
R operator(T t1, T t2);
}
# 测试
public class Main {
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);
}
}