Java.util。函数.DoubleBinaryOperator 接口与示例
Java 8 中引入了DoubleBinaryOperator接口。它表示对两个双精度值的操作,并将结果作为双精度值返回。它是一个函数式接口,因此可以用作 lambda 表达式或方法引用。它主要用于需要从用户封装操作的情况。
方法:
- applyAsDouble() :此函数采用两个双精度值,执行所需的操作并将结果作为双精度值返回。
public double applyAsDouble(double val1, double val2)
将 DoubleBinaryOperator 接口演示为 lambda 表达式的示例。
// Java program to demonstrate DoubleBinaryOperator
import java.util.function.DoubleBinaryOperator;
public class DoubleBinaryOperatorDemo {
public static void main(String[] args)
{
double x = 7.654;
double y = 5.567;
// Representing addition as
// the double binary operator
DoubleBinaryOperator doubleBinaryOperator
= (a, b) -> { return a + b; };
System.out.println("x + y = "
+ doubleBinaryOperator
.applyAsDouble(x, y));
// Representing subtraction as
// the double binary operator
doubleBinaryOperator
= (a, b) -> { return a - b; };
System.out.println("x - y = "
+ doubleBinaryOperator
.applyAsDouble(x, y));
// Representing multiplication as
// the double binary operator
doubleBinaryOperator
= (a, b) -> { return a * b; };
System.out.println("x * y = "
+ doubleBinaryOperator
.applyAsDouble(x, y));
// Representing division as
// the double binary operator
doubleBinaryOperator
= (a, b) -> { return a / b; };
System.out.println("x / y = "
+ doubleBinaryOperator
.applyAsDouble(x, y));
// Representing remainder operation
// as the double binary operator
doubleBinaryOperator
= (a, b) -> { return a % b; };
System.out.println("x % y = "
+ doubleBinaryOperator
.applyAsDouble(x, y));
}
}
输出:
x + y = 13.221
x - y = 2.0869999999999997
x * y = 42.609818000000004
x / y = 1.3748877312735763
x % y = 2.0869999999999997
参考: https: Java/util/函数/DoubleBinaryOperator.html