如何在 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 次浏览

开启你的职业

完成课程后获取认证

开始
广告