What is the DoubleSupplier functional interface in Java?

DoubleSupplier is a functional interface that produces results of type double without accepting any inputs. The results produced each time can be the same or different. The interface contains one method, getAsDouble().

The DoubleSupplier interface is defined in the java.util.function package. To import the DoubleSupplier interface, check the following import statement.

import java.util.function.DoubleSupplier;

getAsDouble()

The getAsDouble() method returns a result of type double every time it’s invoked. This is the functional method of the interface.

Syntax

double getAsDouble()

Parameters

The method has no parameters.

Returns

The method returns the generated result of type double.

Code

The following is an example of the code for the DoubleSupplier interface:

import java.util.Random;
import java.util.function.*;
public class Main{
public static void main(String[] args) {
// DoubleSupplier interface implementation that generates random double value
DoubleSupplier randomSupplier = () -> new Random().nextDouble();
int count = 5;
// Calling getAsDouble method to get the random value
while(count-- > 0) System.out.println(randomSupplier.getAsDouble());
}
}

In the above code, we create an implementation of the DoubleSupplier interface that generates a random double value every time the method getAsDouble() is invoked. The getAsDouble() method is called five times to produce five random double values using the while loop.

Free Resources