DoubleSupplier 接口是java.util.function包中定义的 内置功能接口。该功能接口不需要任何输入,但是会产生双值输出。DoubleSupplier 接口可用作lambda 表达式 和方法 引用的分配目标。 此接口仅包含一个抽象方法:getAsDouble()。
@FunctionalInterfacepublic interface DoubleSupplier { double getAsDouble(); }
import java.util.concurrent.ThreadLocalRandom; import java.util.function.DoubleSupplier; public class DoubleSupplierLambdaTest { public static void main(String args[]) { DoubleSupplier getRandomDouble = () -> { // lambda 表达式 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; //方法引用 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