如何使用 Java 中的 Lambda 和方法引用来实现 IntToDoubleFunction?
IntToDoubleFunction 是 java.util.function 包中的一个函数接口。此函数接口接受一个**整型**参数并产生一个**双精度**结果。IntToDoubleFunction 可用作**lambda 表达式**或**方法引用**的赋值目标。它只包含一个抽象方法:applyAsDouble()。
语法
@FunctionalInterface
interface IntToDoubleFunction {
double applyAsDouble(int value);
}Lambda 表达式的示例
import java.util.function.IntToDoubleFunction;;
public class IntToDoubleLambdaTest {
public static void main(String[] args) {
IntToDoubleFunction getDouble = intVal -> { // lambda expression
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; // method reference
System.out.println(result.applyAsDouble(50));
System.out.println(result.applyAsDouble(100));
}
static Double convertIntToDouble(int value) {
return value / 10d;
}
}输出
5.0 10.0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP