January 19, 2019

Implement java.util.function.DoubleSupplier to return random numbers – java 11 and above

java.util.function.DoubleFunction is a Functional Interface.

It has one abstract method, which takes no input but returns a double value.

It can be used as a supplier of double values, and it can be used to create a doublestream

  1. double getAsDouble() :- it returns a double value, that’s all it’s declaration says.

In this article, we will write an implementation, which returns a random number.

DoubleSupplier rand = Math::random;

We used method referencing to return random number. Those who don’t know, Math.random returns a value between 0.0 to 1.0.

And we can multiply the return value by an integer – X to get a random number between 0.0 to X.

(rand.getAsDouble() * 100)

The above code returns a random value between 0.0 to 100.0.

We can run the above code in a loop 10-times to see the variation in result.

Complete Code :-

import java.util.function.DoubleSupplier;
import static java.lang.System.out;

public class DoubleSupplierTest {
    public static void main(String ... args) {
        //Lambda which returns a random number                                                                                                                                                               
        DoubleSupplier rand = Math::random;

        //print random number                                                                                                                                                                                
        for(int i = 0; i < 10; ++i) {
            out.println("random number between 1 to 100 - " + (rand.getAsDouble() * 100) );
        }
    }
}

Output :-

random number between 1 to 100 - 94.67715169930938
random number between 1 to 100 - 10.868200959583184
random number between 1 to 100 - 70.66146653170898
random number between 1 to 100 - 19.21242680675147
random number between 1 to 100 - 22.630408249996357
random number between 1 to 100 - 78.70537350189699
random number between 1 to 100 - 90.24089926128889
random number between 1 to 100 - 70.92636000175175
random number between 1 to 100 - 84.60645160248119
random number between 1 to 100 - 80.92050003712255