java+lamda+传参,如何在Java中将lambda表达式作为方法参数传递?

甲lambda表达式是一个匿名或无名方法在Java中。它不能单独执行,而是用于实现在功能接口中声明的方法。如果要在Java中将lambda表达式作为方法参数传递,则接收的方法参数的类型必须是功能接口type。

示例interface Algebra {

int operate(int a, int b);

}

enum Operation {   ADD, SUB, MUL, DIV}

public class LambdaMethodArgTest {

public static void main(String[] args) {      print((a, b) -> a + b, Operation.ADD);      print((a, b) -> a - b, Operation.SUB);      print((a, b) -> a * b, Operation.MUL);      print((a, b) -> a / b, Operation.DIV);

}

static void print(Algebra alg, Operation op) {      switch (op) {         case ADD:

System.out.println("The addition of a and b is: " + alg.operate(40, 20));

break;         case SUB:

System.out.println("The subtraction of a and b is: " + alg.operate(40, 20));

break;         case MUL:

System.out.println("The multiplication of a and b is: " + alg.operate(40, 20));

break;         case DIV:

System.out.println("The division of a and b is: " + alg.operate(40, 20));

break;

default:

throw new AssertionError();

}

}

}

输出结果The addition of a and b is: 60

The subtraction of a and b is: 20

The multiplication of a and b is: 800

The division of a and b is: 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值