如何在 Java 中使用 lambda 和方法引用实现 ToIntFunction?\n
ToIntFunction<T> 是 java.util.function 包中定义的内置函数接口。此函数接口需要一个参数作为输入,并生成整数结果。可将其用作lambda 表达式 或方法 引用 的赋值目标。ToIntFunction 接口仅包含一个方法applyAsInt()。此方法对给定参数执行操作并返回整数结果。
语法
@FunctionalInterface
public interface ToIntFunction {
int applyAsInt(T value);
}在以下示例中,我们可以通过使用 lambda 表达式和方法引用来实现ToIntFunction<T>。
示例
import java.util.function.ToIntFunction;
import java.time.LocalDate;
public class ToIntFunctionInterfaceTest {
public static void main(String[] args) {
ToIntFunction<Integer> lambdaObj = value -> value * 25; // using lambda expression
System.out.println("The result is: " + lambdaObj.applyAsInt(10));
ToIntFunction<String> lenFn = String::length; // using method reference
System.out.println("The length of a String is: " + lenFn.applyAsInt("tutorialspoint"));
}
}输出
The result is: 250 The length of a String is: 14
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP