如何在 Java 中使用 lambda 表达式和方法引用实现 IntToDoubleFunction?
java 8object oriented programmingprogramming
IntToDoubleFunction 是 java.util.function 包中的一个函数式接口。该函数式接口接受一个 int 值 参数,并返回一个 double 值 的结果。IntToDoubleFunction 可以用作 lambda表达式 或 方法引用 的赋值目标。它只包含一个抽象方法:applyAsDouble()。
语法
@FunctionalInterface interface IntToDoubleFunction { double applyAsDouble(int value); }
Example of Lambda Expression
import java.util.function.IntToDoubleFunction;; public class IntToDoubleLambdaTest { public static void main(String[] args) { IntToDoubleFunction getDouble = intVal -> { // lambda 表达式 double doubleVal = intVal; return doubleVal; }; int input = 25; double result = getDouble.applyAsDouble(input); System.out.println("The double value is: " + result); input = 50; System.out.println("The double value is: " + getDouble.applyAsDouble(input)); input = 75; System.out.println("The double value is: " + getDouble.applyAsDouble(input)); } }
输出
The double value is: 25.0 The double value is: 50.0 The double value is: 75.0
方法引用示例
import java.util.function.IntToDoubleFunction; public class IntToDoubleMethodRefTest { public static void main(String[] args) { IntToDoubleFunction result = IntToDoubleMethodRefTest::convertIntToDouble; // 方法引用 System.out.println(result.applyAsDouble(50)); System.out.println(result.applyAsDouble(100)); } static Double convertIntToDouble(int value) { return value / 10d; } }
输出
5.0 10.0