如何在 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