如何使用 Java 中的 Lambda 和方法引用來實現 IntToDoubleFunction?


IntToDoubleFunctionjava.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

更新於: 2020 年 7 月 14 日

155 次瀏覽

開啟你的職業生涯 

完成課程即可獲得證書

開始入門
廣告