如何在 Java 中使用 lambda 和方法引用实现 DoubleBinaryOperator?
DoubleBinaryOperator 是 java.util.function 包中定义的一个函数式 接口。它接受两个类型为double 的参数作为输入,并产生另一个double 值作为结果。DoubleBinaryOperator 接口可以用作lambda 表达式 或方法 引用 的赋值目标,并且只有一个抽象方法 applyAsDouble()。
语法
@FunctionalInterface public interface DoubleBinaryOperator { double applyAsDouble(double left, double right); }
示例-1
import java.util.function.DoubleBinaryOperator; public class DoubleBinaryOperatorTest { public static void main(String args[]) { // using lambda expression 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
示例-2
import java.util.function.DoubleBinaryOperator; public class DoubleBinaryOperatorTest1 { public static void main(String[] args) { // Using Lambda Expression DoubleBinaryOperator lamdaTest = (d1, d2) -> DoubleBinaryOperatorTest1.mutiply(d1, d2); System.out.println(lamdaTest.applyAsDouble(7, 5)); // Using Method reference 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
广告