Java Random ints() Method
Example
Roll a dice 5 times, and print each number:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
rand.ints(5, 1, 7).forEach(n -> System.out.println(n));
}
}
Note: The output is different each time you run the program. It is always 5 numbers from 1 to 6.
Definition and Usage
The ints() method returns a stream of random int values. A stream (here an IntStream) is a sequence of values that you can go through one by one, for example with forEach(), or count with count().
In the example, ints(5, 1, 7) returns 5 numbers. Each number is at least 1 and less than 7, so it is a number from 1 to 6, like a dice roll.
Tip: To get only one random number, use nextInt().
Syntax
public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound)
There are also versions with fewer parameters: ints(), ints(streamSize) and ints(randomNumberOrigin, randomNumberBound). Without streamSize, the stream never ends.
Parameter Values
| Parameter | Description |
|---|---|
| streamSize | Required. How many numbers the stream has. |
| randomNumberOrigin | Required. The smallest possible number. The numbers can be equal to it. |
| randomNumberBound | Required. The upper limit. The numbers are always less than it. |
Technical Details
| Returns: | An IntStream with streamSize random int values, each at least randomNumberOrigin and less than randomNumberBound. |
|---|---|
| Throws: | IllegalArgumentException - if streamSize is less than 0, or if randomNumberOrigin is not less than randomNumberBound. |
Related Pages
Java How To Generate Random Numbers
Java Lambda Expressions Tutorial
❮ Random Methods