如何在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
热门推荐
10 写给情侣祝福语 浪漫简短
11 拥有爱的祝福语简短
12 理科元旦祝福语大全简短
13 周末思念祝福语大全简短
14 幼儿狗年祝福语大全简短
15 祝福语诗意文案简短
16 许愿星姐妹祝福语简短
17 祝球员赛前祝福语简短
18 国庆求婚祝福语简短精辟