Java 8 ExamplesJava8

Java 8 DoubleSupplier Example

Posted On
Posted By admin

In this blog post, I will be explaining how the DoubleSupplier Java 8 functional interface works. To know more about functional interfaces, you can refer this blog post.

The  DoubleSupplier interface provides a method called getAsDouble This method does not accept any arguments. It returns a Double data type. The DoubleSupplier interface is a specialization of the Supplier interface that returns a double value. To see an example of the Supplier interface, refer to this blog post.

DoubleSupplier example

Consider the following code snippet:

public class DoubleSupplierDemo {

  public static void main(String[] args) {
    DoubleSupplier getRandom = () ->  new Random().nextDouble();
    System.out.println("Random number 1 = "+getRandom.getAsDouble());
    System.out.println("Random number 2 = "+getRandom.getAsDouble());

  }

}

 

Here, we have implemented the DoubleSupplier.getAsDouble method using a lambda expression.  This getAsDouble method simple returns a random double. So when you execute this code, it will print some random double numbers similar to the following:

Random number 1 = 0.06545562920379944
Random number 2 = 0.4493283376525269

You can get the source code for this example along with other code for other Java 8 examples at the Github repository here.



If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment