Java DoubleSupplier Example
May 06, 2020
This page will walk through DoubleSupplier
example. The DoubleSupplier
is the functional interface introduced in Java 8 under the java.util.function
package. The DoubleSupplier
is the double-producing primitive specialization of Supplier
functional interface. The functional method of DoubleSupplier
is getAsDouble()
which returns result of double
datatype. Find the DoubleSupplier
structure from Java doc.
@FunctionalInterface public interface DoubleSupplier { double getAsDouble(); }
DoubleSupplier
can be instantiated using lambda expression and method reference. Here we will provide using DoubleSupplier
in our applications in detail.
Using Lambda Expression
Find the code to instantiateDoubleSupplier
using lambda expression.
DoubleSupplierWithLE.java
package com.concretepage; import java.util.Random; import java.util.function.DoubleSupplier; public class DoubleSupplierWithLE { public static void main(String[] args) { DoubleSupplier randomDs = () -> new Random().nextDouble(); System.out.println(randomDs.getAsDouble()); DoubleSupplier ds = () -> Double.parseDouble("123.0987"); System.out.println(ds.getAsDouble()); DoubleSupplier multiplyDs = () -> { double val1 = 30.23; double val2 = 45.97; return val1 * val2; }; System.out.println(multiplyDs.getAsDouble()); } }
0.3181297141067999 123.0987 1389.6731
Using Method Reference
Find the code to instantiateDoubleSupplier
using method reference.
DoubleSupplierWithMR.java
package com.concretepage; import java.util.Random; import java.util.function.DoubleSupplier; public class DoubleSupplierWithMR { public static void main(String[] args) { DoubleSupplier randomDs = new Random()::nextDouble; System.out.println(randomDs.getAsDouble()); DoubleSupplier dataDs = AppUtil::getWeight; System.out.println(dataDs.getAsDouble()); } } class AppUtil { public static double getWeight() { return 543.675; } }
0.3253742686068438 543.675
Passing as Method Parameter
Here we will passDoubleSupplier
as method parameter.
WithMethodParameter.java
package com.concretepage; import java.util.Random; import java.util.function.DoubleSupplier; import java.util.stream.DoubleStream; public class WithMethodParameter { public static void main(String[] args) { double output = getResult(() -> Double.max(13.56, 13.67)); System.out.println(output); System.out.println("--- With DoubleStream.generate() ---"); DoubleStream doubleStream = DoubleStream.generate(() -> new Random().nextDouble()).limit(5); doubleStream.forEach(v -> System.out.println(v)); } static double getResult(DoubleSupplier ds) { return ds.getAsDouble() * 100; } }
1367.0 --- With DoubleStream.generate() --- 0.6864265876547981 0.4434981124771008 0.7374602376571032 0.485964623869068 0.7673219107958418