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

更新於: 14-7-2020

234 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告