展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

⾃定义lambda接⼝

定义⼀个函数式接⼝ 需要标注此接⼝ @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);
}
}
posted @   DogLeftover  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示