我是java8的新手。只想知道,这是编写Java 8的正确方法,并建议相对于Java8函数式编程是否可以进一步改进给定的代码?
public class OperationByJava8 {
public int add(int a, int b) {
Operation op = (num1, num2) -> num1 + num2;
return op.operate(a, b);
}
public int subtract(int a, int b) {
Operation op = (num1, num2) -> num1 - num2;
return op.operate(a, b);
}
public int multiply(int a, int b) {
Operation op = (num1, num2) -> num1 * num2;
return op.operate(a, b);
}
public int devide(int a, int b) {
Operation op = (num1, num2) -> {
if (num2 == 0) {
throw new IllegalArgumentException("denominator cannot be zero");
}
return num1 / num2;
};
return op.operate(a, b);
}
public static void main(String[] args) {
OperationByJava9 op = new OperationByJava9();
System.out.println(" Addition(12, 12) :" + op.add(12, 12));
System.out.println(" Subtract(12, 12) :" + op.subtract(12, 12));
System.out.println(" Multiply(12, 12) :" + op.multiply(12, 12));
System.out.println(" Devide (12, 12) :" + op.devide(12, 12));
}
}
@FunctionalInterface
interface Operation {
int operate(int a, int b);
}
答案 0 :(得分:2)
您的方法完全可以,而且很好。
如果要进一步减少代码,可以按如下所示创建一个函数,用于加,减和乘。
public int apply(int a, int b, IntBinaryOperator func) {
return func.applyAsInt(a, b);
}
但是随后您需要为除法功能创建一个单独的功能,以便在第二个参数为IllegalArgumentException
的情况下抛出0
异常。
请注意,我已使用IntBinaryOperator
功能界面来避免创建Operation
接口,但是如果后者更有意义,则可以保留该接口。
或者,您可以内联定义函数,然后调用它们:
IntBinaryOperator add = (num1, num2) -> num1 + num2;
IntBinaryOperator subtract = (num1, num2) -> num1 + num2;
IntBinaryOperator multiply = (num1, num2) -> num1 + num2;
IntBinaryOperator division = (num1, num2) -> {
if (num2 == 0)
throw new IllegalArgumentException("denominator cannot be zero");
return num1 / num2;
};
System.out.println(" Addition(12, 12) :" + add.applyAsInt(12, 12));
System.out.println(" Subtract(12, 12) :" + subtract.applyAsInt(12, 12));
System.out.println(" Multiply(12, 12) :" + multiply.applyAsInt(12, 12));
System.out.println(" Devide (12, 12) :" + division.applyAsInt(12, 12));