【发布时间】:2015-11-11 13:12:06
【问题描述】:
这个 lambda 表达式非常适合具有两个操作数(a 和 b)的数学运算。
public class Math {
interface IntegerMath {
int operation(int a, int b);
}
private static int apply(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " + apply(40, 2, addition));
System.out.println("20 - 10 = " + apply(20, 10, subtraction));
}
}
如何通过可能的一元操作来增强这个类,例如
IntergerMath square = (a) -> a * a;
?
【问题讨论】:
标签: java lambda interface java-8 operator-overloading