Using the ints() method of Random class
We can also use the ints()
method of the Random class to generate a stream of random integers within a range.
Here is the code to generate the stream:
Random r = new Random();
IntStream stream = r.ints(5, 100, 120);
Here, the ints()
method takes three parameters first the count
parameter, which defines how many integers we want to generate, and the bound
parameter, which defines the range. For example, in our code, the bound
parameter is from 100 to 120. It is an inclusive minimum (100) and an exclusive maximum(120) parameter.
After creating this stream, we can consume it using forEach()
or collect to a collection like List or array.
Here is code that uses the ints()
method to generate five random integers between 150 and 2000:
int min = 150; //defining the minimum range
int max = 2000; //defining the maximum range
Random r = new Random();
IntStream stream = r.ints(5, min, max);//Generating the random stream
int randomNum = stream.findFirst().getAsInt();//Getting the first value from stream
System.out.print("The random number is: " + randomNum);//Printing the random number
To execute this method, run the following commands in your terminal:
$ cd project
$ touch RandomNumbers.java
// paste the code
$ javac RandomNumbers.java
$ java RandomNumbers