如何在 Java 中使用 lambda 和方法引用来实现 IntToLongFunction?
IntToLongFunction 是java.util.function包中的内置函数式接口。此函数式接口接受一个Int 值参数并产生一个long 值结果。IntToLongFunction 接口可以用作lambda 表达式或方法 引用的赋值目标。它只包含一个抽象方法:applyAsLong()。
语法
@FunctionalInterface interface IntToLongFunction { long applyAsLong(int value); }
Lambda 表达式的示例
import java.util.function.IntToLongFunction; public class IntToLongFunctionLambdaTest { public static void main(String args[]) { IntToLongFunction getLong = intVal -> { // lambda expression long longVal = intVal; return longVal; }; int input = 40; long result = getLong.applyAsLong(input); System.out.println("The long value is: " + result); input = 75; System.out.println("The long value is: " + getLong.applyAsLong(input)); input = 90; System.out.println("The long value is: " + getLong.applyAsLong(input)); } }
输出
The long valus is: 40 The long valus is: 75 The long valus is: 90
方法引用的示例
import java.util.function.IntToLongFunction; public class IntToLongFunctionMethodRefTest { public static void main(String args[]) { IntToLongFunction result = IntToLongFunctionMethodRefTest::convertIntToLong; // method reference System.out.println(result.applyAsLong(75)); System.out.println(result.applyAsLong(45)); } static Long convertIntToLong(int value) { return value / 10L; } }
输出
7 4
广告