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 表达式 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; //方法引用 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