DoubleBinaryOperator是中定义的函数接口java.util.function函数包裹。它接受两个double类型的参数作为输入,并生成另一个double值。DoubleBinaryOperator接口可以用作lambda表达式或方法引用的赋值目标,并且只有一个抽象方法applyAsDouble()。
语法@FunctionalInterface
public interface DoubleBinaryOperator {
double applyAsDouble(double left, double right);
}
示例1import java.util.function.DoubleBinaryOperator;
public class DoubleBinaryOperatorTest {
public static void main(String args[]) { //使用lambda表达式
DoubleBinaryOperator sum = (d1, d2) -> d1 + d2;
DoubleBinaryOperator mul = (d1, d2) -> d1 * d2;
DoubleBinaryOperator div = (d1, d2) -> d1 / d2;
DoubleBinaryOperator sub = (d1, d2) -> d1 - d2;
System.out.println("Sum = " + operate(sum, 15, 10));
System.out.println("Multiplication = " + operate(mul, 15, 10));
System.out.println("Division = " + operate(div, 15, 10));
System.out.println("Subtraction = " + operate(sub, 15, 10));
}
private static double operate(DoubleBinaryOperator operator, double d1, double d2) {
return operator.applyAsDouble(d1, d2);
}
}
输出结果Sum = 25.0
Multiplication = 150.0
Division = 1.5
Subtraction = 5.0
示例2import java.util.function.DoubleBinaryOperator;
public class DoubleBinaryOperatorTest1 {
public static void main(String[] args) { //使用lambda表达式
DoubleBinaryOperator lamdaTest = (d1, d2) -> DoubleBinaryOperatorTest1.mutiply(d1, d2);
System.out.println(lamdaTest.applyAsDouble(7, 5)); // 使用方法引用
DoubleBinaryOperator methodRefTest = DoubleBinaryOperatorTest1::mutiply;
System.out.println(methodRefTest.applyAsDouble(10, 5));
}
public static double mutiply(double d1, double d2) {
return d1 * d2;
}
}
输出结果35.0
50.0