如何在 Java 中使用 lambda 和方法引用实现 LongToDoubleFunction?
LongToDoubleFunction 是内置函数接口,是 java.util.function 包的一部分。此函数接口接受一个长整型参数作为输入,产生双精度类型的结果。LongToDoubleFunction 可用作 lambda 表达式或 方法引用的赋值目标。它只包含一个抽象方法: applyAsDouble()。
语法
@FunctionalInterface interface LongToDoubleFunction { double applyAsDouble(long value); }
Lambda 实例示例
import java.util.function.LongToDoubleFunction; public class LongToDoubleLambdaTest { public static void main(String args[]) { LongToDoubleFunction getDouble = longVal -> { // lambda expression double doubleVal = longVal; return doubleVal; }; long input = 565758L; System.out.println("The input is: " + input); double result = getDouble.applyAsDouble(input); System.out.println("The result is: " + result); } }
输出
The input is: 565758 The result is: 565758.0
方法引用示例
import java.util.function.LongToDoubleFunction; public class LongToDoubleMethodRefTest { public static void main(String args[]) { LongToDoubleFunction result = LongToDoubleMethodRefTest::convertLongToDouble; // method reference System.out.println(result.applyAsDouble(75)); System.out.println(result.applyAsDouble(60)); } static Double convertLongToDouble(long value) { return (double)value / 5; } }
输出
15.0 12.0
广告