如何在 Java 中使用 lambda 和方法引用实现 DoubleUnaryOperator?
DoubleUnaryOperator 是java.util.function包中定义的一个函数接口。该函数式接口希望将double 类型的参数作为输入,但会生成同一 类型的输出。DoubleUnaryOperator 接口可用作lambda 表达式 和方法 引用的赋值 目标 。该接口中包含一个抽象方法:applyAsDouble()、一个静态方法:identity()以及两个默认方法:andThen() 和 compose()。
语法
@FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
}Lambda 表达式范例
import java.util.function.DoubleUnaryOperator;
public class DoubleUnaryOperatorTest1 {
public static void main(String[] args) {
DoubleUnaryOperator getDoubleValue = doubleValue -> { // lambda expression
return doubleValue * 2;
};
double input = 20.5;
double result = getDoubleValue.applyAsDouble(input);
System.out.println("The input value " + input + " X 2 is : " + result);
input = 77.50;
System.out.println("The input value " + input+ " X 2 is : " + getDoubleValue.applyAsDouble(input));
input = 95.65;
System.out.println("The input value "+ input+ " X 2 is : " + getDoubleValue.applyAsDouble(input));
}
}输出
The input value 20.5 X 2 is : 41.0 The input value 77.5 X 2 is : 155.0 The input value 95.65 X 2 is : 191.3
方法引用范例
import java.util.function.DoubleUnaryOperator;
public class DoubleUnaryOperatorTest2 {
public static void main(String[] args) {
DoubleUnaryOperator d = Math::cos; // method reference
System.out.println("The value is: " + d.applyAsDouble(45));
DoubleUnaryOperator log = Math::log10; // method reference
System.out.println("The value is: " + log.applyAsDouble(100));
}
}输出
The value is: 0.5253219888177297 The value is: 2.0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP