如何在 Java 中使用 lambda 和方法引用實現 DoubleSupplier?


DoubleSupplier 介面是 java.util.function 包中定義的一個 內建函式式介面。此函式式介面不期待有任何輸入,但會生成一個雙值輸出。DoubleSupplier 介面可用作lambda 表示式 和方法 引用的賦值目標。此介面僅包含一個抽象方法:getAsDouble()

語法

@FunctionalInterface
public interface DoubleSupplier {
   double getAsDouble();
}

lambda 表示式的示例

import java.util.concurrent.ThreadLocalRandom;
import java.util.function.DoubleSupplier;

public class DoubleSupplierLambdaTest {
   public static void main(String args[]) {
      DoubleSupplier getRandomDouble = () -> {    // lambda expression
         double doubleVal = ThreadLocalRandom.current().nextDouble(0000, 9999);
         return Math.round(doubleVal);
      };
      double randomVal = getRandomDouble.getAsDouble();
      System.out.println("Random Double Generated : " + randomVal);
      System.out.println("Random Double Generated : " + getRandomDouble.getAsDouble());
      System.out.println("Random Double Generated : " + getRandomDouble.getAsDouble());
   }
}

輸出

Random Double Generated : 4796.0
Random Double Generated : 2319.0
Random Double Generated : 7403.0


方法引用的示例

import java.util.function.DoubleSupplier;

public class DoubleSupplierMethodRefTest {
   public static void main(String args[]) {
      DoubleSupplier random = Math::random;   // method reference
      for(int i = 0; i < 5; ++i) {
         System.out.println("random number between 1 to 100: " + (random.getAsDouble() * 100) );
      }
   }
}

輸出

random number between 1 to 100: 65.72186642095294
random number between 1 to 100: 42.389730890035146
random number between 1 to 100: 16.89589518236835
random number between 1 to 100: 45.85184122201681
random number between 1 to 100: 2.626718898776015

更新於: 2020-07-14

387 次瀏覽

開啟你的職業

完成課程後獲取認證

開始
廣告